为什么在 Java 中的 try-with-resources 构造中,资源的 close() 方法在 catch 之前被调用?
2022-09-03 07:29:04
						我碰巧意识到,情况就是这样。请参阅下面的示例:
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." );
        }
    }
}
它打印:
尝试
关闭。
终于被
抓住了
问题
使用资源进行试用旨在避免带有空检查的混乱的最终部分,并避免泄漏资源。为什么在捕获部分之前关闭资源?它背后的原因/想法/局限性是什么?