try-catch-finally 与 try-with-resources的区别

都知道,所有被打开的系统资源,比如流、文件或者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,代码更加简洁,实现了资源自动关闭。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值