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


问题内容

在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()?
}

问题答案:

资源在捕获或最终阻塞之前被关闭。请参阅本教程

try-with-resources语句可以具有catch并最终阻塞,就像普通的try语句一样。在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