问题
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())
?
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/43522560/does-the-catch-in-try-with-resources-cover-the-code-in-parentheses