try-with-resource替代try-catch-finally
估计一大半人还在使用try-catch-finally关闭资源吗,JDK7就可以引用的try-with-resource。简洁明了
实现了 java.lang.AutoCloseable 接口
public class Resource2 implements AutoCloseable{
public void run(){
throw new RuntimeException("run2 failed");
}
@Override
public void close() {
throw new RuntimeException("resource2 closed with exception");
}
}
public class MainApp {
public static void main(String[] args) {
try (Resource resource=new Resource();){
resource.run();
}catch (Exception e){
e.printStackTrace();
}
}
}
运行结果:
run ....
resource closed
疑问来了,底层原理是啥?
public static void main(String[] args) {
try {
Resource resource = new Resource();
Throwable var2 = null;
try {
resource.sayHello();
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (resource != null) {
if (var2 != null) {
try {
resource.close();
} catch (Throwable var11) {
//处理隐藏异常
var2.addSuppressed(var11);
}
} else {
resource.close();
}
}
}
} catch (Exception var14) {
var14.printStackTrace();
}
}
处理异常屏蔽的 var2.addSuppressed(var11);
如果使用try-catch-finally来处理,只打印了最后出现的异常屏蔽,不好作出判断。
public class Resource2 implements AutoCloseable{
public void run(){
throw new RuntimeException("run2 failed");
}
@Override
public void close() {
throw new RuntimeException("resource2 closed with exception");
}
}
public class MainApp {
public static void main(String[] args) {
Resource2 resource2 = null;
try {
resource2 = new Resource2();
resource2.run();
}
finally {
if (resource2 != null) {
resource2.close();
}
}
}
}
换成try-with-resource
public class MainApp {
public static void main(String[] args) {
try (Resource resource=new Resource();Resource2 resource2=new Resource2()){
resource.run();
resource2.run();
}catch (Exception e){
e.printStackTrace();
}
}
}
异常信息中多了一个Suppressed的提示,告诉我们这个异常其实由两个异常组成,异常是被Suppressed【屏蔽】的异常