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

时间:2014-06-09 21:08:09

标签: java java-7 finally try-with-resources

在Java 7的资源试用中,我不知道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()?
}

2 个答案:

答案 0 :(得分:46)

资源在catch或finally块之前关闭。请参阅此tutorial

  

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

答案 1 :(得分:0)

finally块是要执行的最后一个:

  

此外,所有资源都将被关闭(或试图被关闭)   ),直到执行finally块时为止   最终关键字的含义。

JLS 13的报价; 14.20.3.2. Extended try-with-resources