在Oracle Java documentation on try-with-resources中写有以下内容:
try-with-resources语句可以像普通的try语句一样有catch和finally块。在try-with-resources语句中,在声明的资源关闭后运行任何catch或finally块。
因此,根据文档,如果在尝试关闭资源时发生异常,我老实说试图以某种方式对这段悲伤的消息做出反应,如下所示:
try (OutputStream os = new SampleStream(true)) {
os.write(0); // both this and closing can throw IOWriteException
}
catch (IOWriteException e) {
//do something wise;
}
在关闭问题时,catch块将等待永远关闭。
我知道,实际上并非如此,并且可以捕获关闭时的try-with-resources异常。但是,所提到的规则应该重新制定。怎么样?
我知道,实际上并非如此,并且可以捕获关闭时的try-with-resources异常。
正确以及初始化资源。
我认为the extended try-with-resources part of the JLS可以帮助重新制定这个非常尴尬的解释。
虽然关于finally
声明的部分是相当正确的。
我们可以说:
try-with-resources语句中的catch
语句允许捕获在此语句的任何部分抛出的兼容异常,即1)在资源初始化期间,2)在资源关闭任何资源期间或3)通过在try-with-resources机构。
关于finally
声明,它将在资源关闭(或试图)之后执行。
参考:
14.20.3.2。扩展的资源尝试
具有至少一个
catch
子句和/或finally
子句的try-with-resources语句称为扩展的try-with-resources语句。扩展的try-with-resources语句的含义:
try ResourceSpecification
Block
Catchesopt
Finallyopt
通过以下翻译给出了嵌套在
try-catch
或try-finally
或try-catch-finally
语句中的基本try-with-resources语句(§14.20.3.1):
try {
try ResourceSpecification
Block
}
Catchesopt
Finallyopt
翻译的效果是将
ResourceSpecification
置于try
声明的“内部”。这允许扩展的try-with-resources语句的catch
子句捕获由于任何资源的自动初始化或关闭而导致的异常。此外,在执行
finally
块时,所有资源都将被关闭(或试图关闭),这与finally
关键字的意图保持一致。