38

在 Java 7 的 try-with-resources 中,我不知道 finally 块和自动关闭发生的顺序。顺序是什么?

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()?
}
4

2 回答 2

57

资源在 catch 或 finally 阻塞之前关闭。请参阅本教程

try-with-resources 语句可以像普通的 try 语句一样有 catch 和 finally 块。在 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
于 2014-06-09T21:09:00.820 回答
0

finally 块是最后被执行的:

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

引自 JLS 13;14.20.3.2。扩展 try-with-resources

于 2019-09-18T14:16:48.693 回答