gpt4 book ai didi

java - 如果构造函数抛出异常,是否不调用 try-with-resources 习惯用法的 close 方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:25 25 4
gpt4 key购买 nike

我有一个基类 Base 和一个扩展它的子类 ChildBase 实现了 java.lang.AutoCloseable

假设 Child 的构造函数抛出一个 Foo

现在考虑

try (Base c = new Child()){
/*Some code*/
} catch (final Foo e){
/*Some more code*/
}

如果抛出异常,是否调用Base#close方法?它不在我的机器上,但这是 JLS 标准化的东西吗?

最佳答案

是的,close 不会被调用。这在 JLS section 14.20.3 中指定:

Resources are initialized in left-to-right order. If a resource fails to initialize (that is, its initializer expression throws an exception), then all resources initialized so far by the try-with-resources statement are closed. If all resources initialize successfully, the try block executes as normal and then all non-null resources of the try-with-resources statement are closed.

Resources are closed in the reverse order from that in which they were initialized. A resource is closed only if it initialized to a non-null value. An exception from the closing of one resource does not prevent the closing of other resources. Such an exception is suppressed if an exception was thrown previously by an initializer, the try block, or the closing of a resource.

在这种情况下,构造函数中会抛出异常,因此资源不会初始化为非空值。因此,不会调用 close 方法。

关于java - 如果构造函数抛出异常,是否不调用 try-with-resources 习惯用法的 close 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34678538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com