加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java7后try语句的优化

发布时间:2020-12-15 05:23:47 所属栏目:Java 来源:网络整理
导读:原始的写法 先来看一段老代码 OutputStream out = null;try { out = response.getOutputStream()} catch (IOException e1) { e.printStackTrace();}finally{ try { if(out != null){ out.close(); } } catch (IOException e2) { e.printStackTrace(); }} 这

原始的写法

  先来看一段老代码

OutputStream out = null;
try {
   out = response.getOutputStream()
} catch (IOException e1) {
    e.printStackTrace();
}finally{
    try {
        if(out != null){
            out.close();
        }
    } catch (IOException e2) {
        e.printStackTrace();
    }
}

  这个输出流使用了try/catch/finally,写法繁琐,并且在关闭的时候也有可能会抛出异常,异常e2 会覆盖掉异常e1 。

?

优化后的写法

  Java7提供了一种try-with-resource机制,新增自动释放资源接口AutoCloseable

  在JDK7中只要实现了AutoCloseable或Closeable接口的类或接口,都可以使用try-with-resource来实现异常处理和资源关闭异常抛出顺序。异常的抛出顺序与之前的不一样,是先声明的资源后关闭。

  上例中OutputStream实现了Closeable接口,可以修改成:

try(OutputStream out = response.getOutputStream()) {
    //
} catch (IOException e) {
    e.printStackTrace();
}

//如果有多个OutputStream,可以加分号
try(OutputStream out1 = response.getOutputStream();
    OutputStream out2 = response.getOutputStream()) {
    //
} catch (IOException e) {
    e.printStackTrace();
}

?  这样写还有一个好处。能获取到正确的异常,而非资源关闭时抛出的异常。

  还有一点要说明的是,catch多种异常也可以合并成一个了

catch (IOException | SQLException e) {
    e.printStackTrace();
}

try-with-resource的优点

  1、代码变得简洁可读
  2、所有的资源都托管给try-with-resource语句,能够保证所有的资源被正确关闭,再也不用担心资源关闭的问题。
  3、能获取到正确的异常,而非资源关闭时抛出的异常

?

  Closeable 接口继承了AutoCloseable 接口,都只有一个close()方法,自己新建的类也可以实现这个接口,然后使用try-with-resource机制

public interface AutoCloseable {
    void close() throws Exception;
}
public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读