Home > other >  2 try blocks and one catch block in Java?
2 try blocks and one catch block in Java?

Time:10-10

I'm learning about Java and exception handling and the try catch block. 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);
        }

CodePudding user response:

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 having try without catch or finally (and compiler will not allow that).

Note that in case of try-with-resources try(myResource){}, you do have an implicit finally-block, therefore even without a catch-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.

CodePudding user response:

EDIT

Looks like java changed behavior of try-with-resource, so my answer is no longer valid.

It did explains why you can see double try in some old tutorials.

ORIGINAL POST

Try with resources is syntactic sugar.

try(A a = foo()){
   bar();
} catch (E e) {
}

is equivalent of

A a = foo();
try {
   bar();
} catch (E e) {
} finally {
   a.close();
}

Which mean exception thrown from foo won't be caught. therefore you need another try ... catch.

  • Related