快乐随行

导航

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


posted on 2021-04-13 09:06  快乐随行  阅读(181)  评论(0编辑  收藏  举报