小编Rin*_*PJr的帖子

声明多个有效的最终资源时,try-with-resource 不安全吗?

从 Java 9 开始,我们可以在 try-with-resources 中有效地使用最终变量。

下面的示例展示了一种资源初始化引发异常的情况。

    public static void main(String[] args) {
        Resource1 r1 = new Resource1();
        Resource2 r2 = new Resource2(); // exception will be thrown
        try (r1; r2) {
            System.out.println("TryWithResources.main() try");
        } catch (Exception e) {
            System.out.println("TryWithResources.main() catch");
        }
    }
    
    static class Resource1 implements AutoCloseable {
        @Override
        public void close() throws Exception {
            System.out.println("TryWithResources.Resource1.close()");
        }
    }
    
    static class Resource2 implements AutoCloseable {
        public Resource2() {
            throw new RuntimeException();
        }
        @Override
        public void close() throws Exception {
            System.out.println("TryWithResources.Resource2.close()"); …
Run Code Online (Sandbox Code Playgroud)

java try-with-resources autocloseable java-9

2
推荐指数
1
解决办法
112
查看次数

标签 统计

autocloseable ×1

java ×1

java-9 ×1

try-with-resources ×1