都知道,所有被打开的系统资源,比如流、文件或者Socket连接等,都需要开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故。
1. 2.先来说说try-catch-finally:
try-catch-finally结构是Java提供来处理异常的,finally中执行关闭资源的方法。它的语法结构如下:
try{
//代码执行区域
}catch(Exception e){
//异常处理区域
}finally{
//无论如何都会执行的代码区域
}
注意:不管try和catch中做了什么处理,finally中无论如何都是会执行。
2. 然后说说try-with-resource:
try-with-resource是JDK1.7引入的一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象)的类,可以使用作为资源。
关闭多个资源举例(一个和多个类似):
public class Exception {
public static void main(String[] args) {
try(Some some = new Some();Other other = new Other()) {
some.doSome();
other.doOther();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
class Some implements AutoCloseable {
void doSome() {
System.out.println("1");
}
@Override
public void close() throws Exception {
System.out.println("some is closed");
}
}
class Other implements AutoCloseable {
void doOther() {
System.out.println("2");
}
@Override
public void close() throws Exception {
System.out.println("other is closed");
}
}
输出结果
1
2
other is closed
some is closed
可以从输出结果中看到在 try 语句中越是最后使用的资源,越是最早被关闭。
在JDK1.9中try-with-resource(声明的变量)做出了改进,可以直接使用。
final Resource resource1 = new Resource("resource1");
Resource resource2 = new Resource("resource2");
try (resource1;resource2) {
// 可以直接使用 resource1 and resource 2.
}
3. 最后总结两种的区别:
(1)try-catch-finally:没有限制条件,在 JDK 7 之前,各种资源操作需要在finally里面手动关闭,还可以用于执行其他代码块;
(2)try-with-resources:在JDK 7中引入try-with-resources,代码更加简洁,实现了资源自动关闭。