gpt4 book ai didi

java - catch block 和资源关闭的真正工作顺序是什么?

转载 作者:行者123 更新时间:2023-11-30 02:02:54 24 4
gpt4 key购买 nike

Oracle Java documentation on try-with-resources上面写着:

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.

因此,根据文档,如果在尝试关闭资源时发生异常,并且我真诚地尝试对这条悲伤的消息做出某种 react ,如下所示:

try (OutputStream os = new SampleStream(true)) {
os.write(0); // both this and closing can throw IOWriteException
}
catch (IOWriteException e) {
//do something wise;
}

在关闭问题时,catch block 将永远等待关闭。

我知道,事实并非如此,并且可以捕获关闭时的 try-with-resources 异常。但随后提到的规则应该重新制定。怎么办?

最佳答案

I know, that really it is not so, and the try-with-resources exception on closing can be caught.

对,还有资源的初始化。

我认为the extended try-with-resources part of the JLS可以帮助重新表述这个相当尴尬的解释。
虽然对于finally语句的部分来说是相当正确的。

我们可以这样说:

try-with-resources 语句中的 catch 语句允许捕获在此语句的任何部分中抛出的兼容异常,即 1) 在资源初始化期间,2) 在任何资源的资源关闭或 3)by 在 try-with-resources 主体中执行的语句
对于finally 语句,它将在资源关闭后执行(或尝试关闭)。

引用:

14.20.3.2. Extended try-with-resources

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
Catchesopt
Finallyopt

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

try {
try ResourceSpecification
Block
}
Catchesopt
Finallyopt

The effect of the translation is to put the ResourceSpecification "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 - catch block 和资源关闭的真正工作顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238654/

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