资源是否在最终之前或之后关闭?

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

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块之前关闭。 请参阅本教程 。

try-with-resources语句可以像普通的try语句一样有catch和finally块。 在try-with-resources语句中,在声明的资源关闭后运行任何catch或finally块。

要评估这是一个示例代码:

 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