zoukankan      html  css  js  c++  java
  • JAVA 中的异常(4)- 异常的处理方式三:try-with-resource

    Java 1.7中新增的try-with-resource语法糖来很好的解决这种因为关闭资源引起的异常屏蔽问题。

    public void testExcep(){
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(new File("1.txt")));
            out = new BufferedOutputStream(new FileOutputStream(new File("2.txt")));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    为了释放资源,我们不得不这样写。但当我们熟悉try-with-resource语法,我们可以这样写。

    public static void main(String[] args) {
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("1.txt")));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("2.txt")))) {
            // 处理输入数据并输出
        } catch (IOException e) {
            // 捕捉异常并处理
        }
    }
    

    在try子句中能创建一个资源对象,当程序的执行完try-catch之后,运行环境自动关闭资源。

    代码写起来简洁,也会解决掉屏蔽异常问题。

    当然也要注意,在使用try-with-resource的过程中,一定需要了解资源的close方法内部的实现逻辑。否则还是可能会导致资源泄露。


    作者:快乐随行

    https://www.cnblogs.com/jddreams/p/14281900.html


    ---- 作者:快乐随行 著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明原文作者及出处。 ----
  • 相关阅读:
    记一次在Windows10桌面环境搭建Jekins的吐血经历
    Windows系统下的输入法选择
    Linux后台进程启停脚本模板
    crontab采坑总结
    编程软件仓库集合
    CentOS7安装Chrome及驱动
    不错的“淘宝”网站
    软件下载网站集合
    在线API集合
    在线教程集合
  • 原文地址:https://www.cnblogs.com/jddreams/p/14282921.html
Copyright © 2011-2022 走看看