try-with-resources 中的 catch 是否覆盖了括号中的代码?

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

documentation 不清楚 try-with-resources 之后的 catch 是否涵盖了初始化部分。

换句话说,给定这个代码片段:

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

如果在 getSomeStream() 抛出 IOException,我的 catch 会被调用吗?

或者 catch 是否只覆盖大括号内的块,即 System.out.println(in.read())

是的,它被覆盖了。 运行

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

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

打印

IOException: null

所以是的,初始化部分抛出的Exception被catch块捕获了。

来自 JLS,您的示例是一个扩展的 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.

在那种情况下:

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.

所以是的,异常将被您的 catch 块捕获。

Oracle教程是权威的,但不规范。联合会 http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.3.2 完全回答你的问题:是的。

阅读精细手册。