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())
?
Yes, it is covered. Running
with
prints
So yes, the Exception thrown in the initialization part is caught in the catch block.
The Oracle tutorials are authoritative but not normative. The JLS http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.3.2 answers your question completely: Yes.
Read the Fine Manual.
From the JLS, your example is an extended try-with-resources.
In that case :
So yes, the exception will be caught by your
catch
block.