【发布时间】:2014-09-23 07:09:29
【问题描述】:
我碰巧意识到,情况就是这样。请参阅下面的示例:
public class AutoClosableTest {
public static void main(String[] args) throws Exception {
try (MyClosable instance = new MyClosable()) {
if (true) {
System.out.println( "try" );
throw new Exception("Foo");
}
} catch( Exception e ) {
System.out.println( "Catched" );
} finally {
System.out.println( "Finally" );
}
}
public static class MyClosable implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println( "Closed." );
}
}
}
打印出来:
试试
关闭。
抓到
终于
问题
try-with-resources 旨在避免带有 null 检查的混乱 finally 部分,并避免资源泄漏。为什么在 catch 部分之前关闭资源?其背后的原因/想法/局限是什么?
【问题讨论】:
标签: java try-with-resources autocloseable