Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the catch in try-with-resources cover the code in parentheses?

It is unclear from the documentation if a catch following a try-with-resources covers the initialization part or not.

In other words, given this code fragment:

    try (InputStream in = getSomeStream()) {
        System.out.println(in.read());
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
    }

Would my catch be invoked if an IOException is thrown inside getSomeStream()?

Or does the catch only cover the block inside curly braces, i.e. System.out.println(in.read())?

like image 717
rustyx Avatar asked Apr 20 '17 14:04

rustyx


People also ask

Can we have catch block for try with resource?

Note: A try -with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.

Which of the following is a correct statement about try-with-resources statement in java 9?

The try-with-resources statement is a try statement with one or more resources duly declared. Here resource is an object which should be closed once it is no more required. The try-with-resources statement ensures that each resource is closed after the requirement finishes.

Can we write code in catch block?

No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

Does try-with-resources always close?

Exception Handling If an exception is thrown from within a Java try-with-resources block, any resource opened inside the parentheses of the try block will still get closed automatically.


2 Answers

From the JLS, your example is an extended try-with-resources.

A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

In that case :

The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

So yes, the exception will be caught by your catch block.

like image 131
Arnaud Avatar answered Nov 14 '22 22:11

Arnaud


Yes, it is covered. Running

try (InputStream in = getSomeStream()) {
  System.out.println(in.read());
} catch (IOException e) {
  System.err.println("IOException: " + e.getMessage());
}

with

static InputStream getSomeStream() throws IOException {
  throw new IOException();
}

prints

IOException: null

So yes, the Exception thrown in the initialization part is caught in the catch block.

like image 43
f1sh Avatar answered Nov 14 '22 22:11

f1sh