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

dje*_*lin 33 java finally java-7 try-with-resources

在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()?
}
Run Code Online (Sandbox Code Playgroud)

Jig*_*shi 48

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


    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

try exit
closing
catch
finally
Run Code Online (Sandbox Code Playgroud)

  • 疯狂的。因此,当需要资源来处理捕获时,Try-with-resources 不能很好地替代 try-catch-finally。 (4认同)
  • catch 块可能需要资源来完成它的任务。 (2认同)