编程语言
首页 > 编程语言> > java – try-with-resource vs finally优先级

java – try-with-resource vs finally优先级

作者:互联网

try-with-resource构造的优先规则是什么?这是一个例子(注意:所有提到的类都实现了Closeable):

try (Page closeablePage = page;
     PipedOutputStream out = outs;
     SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) {
  // do stuff
} finally {
  callback.run();
}

回调何时运行?我的假设是:

>关闭SequenceWriter
>关闭PipedOutputStream
>关闭页面
>运行回调

我错了吗?

解决方法:

在try-with-resources语句关闭所有资源后,将运行finally块.

这在JLS section 14.20.3.2中指定,引用:

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.

此外,所有资源都以反向声明顺序关闭.引用section 14.20.3(强调我的):

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.

这意味着您的假设是正确的.

标签:java,try-with-resources
来源: https://codeday.me/bug/20190611/1221486.html