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())
?
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.
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.
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With