Im thinking about using this code without try catch. can I use it that way. is it a bad practise to use it here without try catch.
without try catch
public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get("D:" + uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
InputStream inputStream = multipartFile.getInputStream();
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
}
}
or
with try catch
public static void saveFile(String uploadDir, String fileName, MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get("D:" + uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioException) {
System.out.println(ioException);
}
}
Im expecting to reduce the line of codes here…
Shenan Vindinu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Exceptions are the preferred way to tell your caller that you (your method) could not fulfill your task. For your caller, it’s necessary to know whether the file was saved, so it can abort its further steps (or take other appropriate action) in case the file wasn’t saved.
So, the first version is okay, in that your caller gets a notification that trying save the file didn’t work (by simply receiving the exception).
The second one is plain WRONG. It’s primarily the method caller that has to be informed about the failure, not some user reading console output.