zoukankan      html  css  js  c++  java
  • Java7后try语句的优化

    原始的写法

      先来看一段老代码

    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;
    }
  • 相关阅读:
    数据库语句中(+)是什么意思
    MySQL的存储引擎(二)解决Warning Code : 3719 'utf8' is currently an alias for the character set UTF8MB3,...
    MSQL存储引擎(一)
    fastjson的使用,在redis里面存list
    js的发展历史,笔记
    spring的断言工具类Assert的基本使用
    httpclient的使用
    nginx的反向代理
    使用 Redis 连接池的原因
    springboot的yml自定义值的笔记
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/java7try.html
Copyright © 2011-2022 走看看