Are resources closed before or after the finally?

浪子不回头ぞ 提交于 2019-11-27 21:06:39

问题


In Java 7's try-with-resources, I don't know which order the finally block and the auto-closing happens. What's the order?

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

回答1:


The resource gets closed before catch or finally blocks. See this tutorial.

A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

To evaluate this is a sample code:

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");
        }


    }
}

Output:

try exit
closing
catch
finally



回答2:


The finally block is the last to be executed:

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.

Quote from the JLS 13; 14.20.3.2. Extended try-with-resources:



来源:https://stackoverflow.com/questions/24129088/are-resources-closed-before-or-after-the-finally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!