Java - 带参的异常处理模块try(xxx){...}

  带资源的try语句(try-with-resource)的最简形式为:


 try(Resource res = xxx)//可指定多个资源
   {
      //do something
   }

  try块退出时,会自动调用res.close()方法,关闭资源。

  其实这样做的原因,主要是为了不在finally里面,嵌套做非空判断以及关闭各种流;其实我们还有其他的办法来在filnally里面关闭流,而且关于非空判断,也会帮我们做掉;

     try{
            fileOutputStream = new FileOutputStream(file);
            printStream = new PrintStream(fileOutputStream);
            //将字符串写入文件
            printStream.println(sb.toString());
        } catch (IOException e) {
            log.error("Exception writing file, please check it. path:{} {}",file.getPath(),e);
        } finally {
            IOUtils.closeQuietly(fileOutputStream);
            IOUtils.closeQuietly(printStream);
        }
  org.apache.commons.io.IOUtils.closeQuietly 方法源码如下: 
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException var2) {
        }

    }

     不是很愉快的解决了我们在finally里面嵌套做非空判断的烦恼,而且还继续保持原来的try-cache-finally的代码编写习惯,懒人专用。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值