try-with-resource vs finally 优先级

try-with-resource vs finally precedence

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

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

什么时候回调运行?我的假设是:

  1. 关闭SequenceWriter
  2. 关闭PipedOutputStream
  3. 关闭Page
  4. 运行回调

我错了吗?

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

这是在 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.

这意味着你的假设是正确的。