Discuss / Java / 关于try-with-resources语法糖的思考

关于try-with-resources语法糖的思考

Topic source

涵哥0201712

#1 Created at ... [Delete] [Delete and Lock User]

源代码:

try (FileInputStream is = new FileInputStream("123")) {
    System.out.println(1);
}

desugar:

FileInputStream is = new FileInputStream("123");
Throwable var2 = null;

try {
    System.out.println(1);
} catch (Throwable var11) {
    var2 = var11;    
    throw var11;
} finally {
    if (is != null) {
        if (var2 != null) {
            try {
                is.close();            
            } catch (Throwable var10) {
                var2.addSuppressed(var10);            
            }
        } else {
            is.close();        
        }
    }
}

Closeable的对象在关闭过程中如果抛出了异常,怎么避免丢失这个异常信息呢?可以看到JDK的实现也是利用了addSuppressed方法


  • 1

Reply