资源在finally之前还是之后关闭?

40

在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()?
}
2个回答

61

在 catch 或 finally 块之前,该资源已被关闭。请参见此教程

与普通的 try 语句一样,try-with-resources 语句也可以有 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

4
尝试使用try-with-resources不能完全替代try-catch-finally,特别是在需要利用catch处理资源时。这样做可能会出现问题。 - Gustavo
1
资源不需要在 catch 块中处理。 - jmj
2
捕获块可能需要资源来完成其任务。 - Gustavo
这很不好。我原以为在使用 try-with-resources 处理 SQL 连接时可以在 finally 中调用 rollback() 方法,但事实并非如此。建议参考 https://dev59.com/H3VC5IYBdhLWcg3wqzLV#218495。 - Zyl

1
根据JLS 13; 14.20.3.2. 扩展的try-with-resources
最后执行finally块:
此外,所有资源都将在finally块执行时关闭(或尝试关闭),以保持finally关键字的意图。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接