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

标签 java try-with-resources

不清楚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 是否只覆盖大括号内的 block ,即 System.out.println(in.read())

最佳答案

来自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 block 捕获。

关于java - try-with-resources 中的 catch 是否覆盖了括号中的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43522560/

相关文章:

Java Try With Resources 不适用于赋值?

java - 返回尝试资源。这是 JVM 的正确行为吗?

java - 想要将程序作为框架分发,但担心依赖项的数量

java - 设置 JFrame 的最大尺寸

Java 邮件异常错误;

java - 尝试使用此语言级别不支持的资源

java - 将绝对路径名转换为用作子路径的最佳方法是什么?

java - 如何判断 JAR 是否是使用 Gradle 构建的?

java - 如何设置 NetBeans 项目属性以使用 Java 7?

java - 尝试使用资源 : Resource leak while closing resources in TWR block