资源是在最终之前还是之后关闭?

2022-09-01 04:31:28

在Java 7的试用资源中,我不知道最终阻止和自动关闭发生的顺序。顺序是什么?

BaseResource b = new BaseResource(); // not auto-closeable; must be stop'ed
try(AdvancedResource a = new AdvancedResource(b)) {

}
finally {
    b.stop(); // will this happen before or after a.close()?
}

答案 1

资源在捕获或最终阻塞之前被关闭。请参阅本教程

使用资源进行 try 语句可以像普通的 try 语句一样具有 catch 和最终块。在 try-with-resources 语句中,任何 catch 或 finally 块都会在声明的资源已关闭后运行。

要对此进行评估,请看一个示例代码:

class ClosableDummy implements Closeable {
    public void close() {
        System.out.println("closing");
    }
}

public class ClosableDemo {
    public static void main(String[] args) {
        try (ClosableDummy closableDummy = new ClosableDummy()) {
            System.out.println("try exit");
            throw new Exception();
        } catch (Exception ex) {
            System.out.println("catch");
        } finally {
            System.out.println("finally");
        }


    }
}

输出:

try exit
closing
catch
finally

答案 2

最后的块是最后执行的块:

此外,在执行 finally 块时,所有资源都将被关闭(或试图关闭),这与 finally 关键字的意图一致。

引用自JLS 13;14.20.3.2. 扩展的资源试用


推荐