gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:03:17 25 4
gpt4 key购买 nike

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

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

最佳答案

资源在 catch 或 finally 阻塞之前关闭。看到这个tutorial .

A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

评估这是一个示例代码:

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

关于java - 资源是在 finally 之前还是之后关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24129088/

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