gpt4 book ai didi

java - 为什么在 Java 的 try-with-resources 构造中 catch 之前调用资源的 close() 方法?

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

我偶然发现,是这样的。请参阅下面的示例:

public class AutoClosableTest {
public static void main(String[] args) throws Exception {
try (MyClosable instance = new MyClosable()) {
if (true) {
System.out.println( "try" );
throw new Exception("Foo");
}
} catch( Exception e ) {
System.out.println( "Catched" );
} finally {
System.out.println( "Finally" );
}
}

public static class MyClosable implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println( "Closed." );
}
}
}

它打印:

try
Closed.
Catched
Finally

问题

try-with-resources 旨在避免带有空检查的困惑 finally 部分,并避免泄漏资源。为什么资源在捕获部分之前关闭?其背后的原因/想法/限制是什么?

最佳答案

答案可以在JLS §14.20.3.2中找到;关键部分是最后两段,尤其是倒数第二段的最后一句(我强调了):

A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

The meaning of an extended try-with-resources statement:

try ResourceSpecification
Block
[Catches]
[Finally]

is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:

try {
try ResourceSpecification
Block
}
[Catches]
[Finally]

The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

关于java - 为什么在 Java 的 try-with-resources 构造中 catch 之前调用资源的 close() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25057208/

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