我碰巧意识到,情况就是这样。请参阅下面的示例:
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 部分之前关闭资源?其背后的原因/想法/限制是什么?