I'm learning about Java and exception handling and the try/catch blocks. And I'm doing an example from YouTube, and I want to ask you if this is a pattern or something when you use 2 try blocks and one catch block:
private List<User> parseCSVFile(final MultipartFile file) throws Exception {
final List<User> users = new ArrayList<>();
try {
try (final BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
final String[] data = line.split(",");
final User user = new User();
user.setName(data[0]);
user.setEmail(data[1]);
user.setGender(data[2]);
users.add(user);
}
return users;
}
} catch (final IOException e) {
logger.error("Failed to parse CSV file {}", e);
throw new Exception("Failed to parse CSV file {}", e);
}
}
I try to understand why this approach is better than using a try and a catch block like this:
try (final BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
final String[] data = line.split(",");
final User user = new User();
user.setName(data[0]);
user.setEmail(data[1]);
user.setGender(data[2]);
users.add(user);
}
return users;
} catch (final IOException e) {
logger.error("Failed to parse CSV file {}", e);
throw new Exception("Failed to parse CSV file {}", e);
}
Two nested
try-blocks in the first code snippet are redundant. When an exception occurs, it would be propagated until the point where it can be handled (or otherwise the execution would terminate).Regarding the usage of
try-blocks, you need to understand that it doesn't make sense havingtrywithoutcatchorfinally(and compiler will not allow that).Note that in case of try-with-resources
try(myResource){}, you do have an implicitfinally-block, therefore even without acatch-block try-with-resources can be useful and perfectly valid from the compiler perspective of view.For more information on exception-handling refer to the official tutorial provided by Oracle.