版权声明:本文为博主原创文章,大家可以随便转载,觉得好给个赞哦。 https://blog.csdn.net/baidu_25310663/article/details/85041469
目录
环境
Java1.7版本及其以后版本
语法
JDK1.7开始,java引入了 try-with-resources 声明,将 try-catch-finally 简化为 try-catch,这其实是一种语法糖,在编译时会进行转化为 try-catch-finally 语句。新的声明包含三部分:try-with-resources 声明、try 块、catch 块。它要求在 try-with-resources 声明中定义的变量实现了 AutoCloseable 接口,这样在系统可以自动调用它们的close方法,从而替代了finally中关闭资源的功能。
作用
关闭在try-catch语句块中使用的资源,需要在ry-with-resources 声明中的实现AutoCloseable 接口的资源。
范例
Java1.7之前写法
public static void main(String[] args) {
FileInputStream file = null;
try {
file = new FileInputStream("D:\\logs\\log-cleaner.log");
System.out.println("ooo");
file.read();
System.out.println("aaa");
} catch (IOException io) {
System.out.println("bbb");
io.printStackTrace();
} catch (Exception e) {
System.out.println("ccc");
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用 try-with-resources异常处理机制
public static void main(String[] args) {
try(FileInputStream file = new FileInputStream("D:\\logs\\log-cleaner.log")){
System.out.println("ooo");
file.read();
System.out.println("aaa");
}catch (IOException io){
System.out.println("bbb");
io.printStackTrace();
}catch (Exception e){
System.out.println("ccc");
e.printStackTrace();
}
}
编译后的class文件,反编译软件jd-gui,下载链接https://download.csdn.net/download/baidu_25310663/10851553
public static void main(String[] paramArrayOfString)
{
try
{
FileInputStream localFileInputStream = new FileInputStream("D:\\logs\\log-cleaner.log"); Object localObject1 = null;
try {
System.out.println("ooo");
localFileInputStream.read();
System.out.println("aaa");
}
catch (Throwable localThrowable2)
{
localObject1 = localThrowable2; throw localThrowable2;
}
finally
{
if (localFileInputStream != null) if (localObject1 != null) try { localFileInputStream.close(); } catch (Throwable localThrowable3) { localObject1.addSuppressed(localThrowable3); } else localFileInputStream.close();
}
} catch (IOException localIOException) {
System.out.println("bbb");
localIOException.printStackTrace();
} catch (Exception localException) {
System.out.println("ccc");
localException.printStackTrace();
}
}
总结
可以增强代码可读性