首页 > 解决方案 > Closeable 和 AutoCloseable close() 方法的执行顺序

问题描述

有人可以向我解释这里发生了什么以及按什么顺序吗?输出对我来说没有任何意义。

输出为 T 1 IOE F。

代码是:

import java.io.Closeable;
import java.io.IOException;

public class TestRes {
    public static void main(String[] args) {
    try (
            MyResource11 r1 = new MyResource11();
            MyResource21 r2 = new MyResource21();
            ) 
        {
            System.out.print("T ");
        } catch (IOException ioe) {
            System.out.print("IOE ");
        } finally {
            System.out.print("F ");
        }
    }
}

class MyResource11 implements AutoCloseable {
    public void close() throws IOException {
        System.out.print("1 ");
    }
}

class MyResource21 implements Closeable {
    public void close() throws IOException {
        throw new IOException();
    }
}

标签: javaioexceptiontry-with-resourcesautocloseable

解决方案


try-with-resources 以与声明它们的顺序相反的顺序关闭资源。所以代码:

  1. 印刷T
  2. try-with-resources 语句试图关闭r2
  3. 这会引发异常
  4. try-with-resources 语句成功关闭r1,输出1
  5. 运行异常块(对于来自 的异常r2)并输出IOE
  6. finally 块运行,输出F

值得阅读JLS 的 try-with-resources 部分,其中包括未解开的 try-with-resources 语句的代码示例(例如,仅带有try/ catch/的等效代码finally)。从那个部分:

资源以与它们初始化时相反的顺序关闭。仅当资源初始化为非空值时才关闭资源。关闭一个资源的异常不会阻止关闭其他资源。如果异常之前由初始化程序、try 块或资源关闭引发,则此类异常将被抑制。


推荐阅读