• 【JavaSE】如何简化Java的异常处理?try-with-resource语句的使用


    try-with-resource语句的使用

    在Java8中新增了try-with-resource语句,是为了确保IO流资源在任何情况下都能被关闭,防止资源泄漏,同时能够大幅简化异常处理的程序。下面将以Java7及之前和Java8及之后的资源管理程序作对比说明 try-with-resource香在哪里。

    1.Java7之前的资源对象管理程序

    如下代码所示,在Java7及之前,为了确保资源在任何情况下都能关闭,finally 代码块要写非常冗长的代码 (第26~41行代码) 。

    由于 fr.close();fw.close(); 自身也会报异常,所以 finally 代码块里还要分别对它们进行 try-catch 一次。如果不分别进行 try-catch 处理,当第30行的 fr.close(); 出现异常时,程序就会中断,后面的 fw.close(); 就没有办法被执行,造成资源泄露。因此关闭资源的代码块就显得非常冗长。

    @Test
    public void testFileReaderAndWriter() {
        FileReader fr = null;
        FileWriter fw = null;
    
        try {
            //1.创建File类的对象,指明读入和写出到的文件
            File srcFile = new File("hello.txt");
            File destFile = new File("hello1.txt");
    
            //2.创建输入流和输出流的对象
            fr = new FileReader(srcFile);
            fw = new FileWriter(destFile);
    
            //3.数据的读入和写出操作
            char[] cbuf = new char[(int) srcFile.length()];
            int len;//记录每次读入到cbuf数组中的字符的个数
            while ((len = fr.read(cbuf)) != -1) {
                //每次写出len个字符
                fw.write(cbuf, 0, len);
            }
    
        } catch (IOException e) {
            e.printStackTrace();
    
        } finally {
            //4.关闭流资源
            try {
                if (fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            //即时上面fr.close()出现异常,下面也会被执行,因为try-catch是真正已经把异常处理掉了
            try {
                if (fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    2.Java8后使用try-with-resource语句进行优化

    使用 try-with-resource 语句很简单,只需在原有的 try-catch 结构的基础上,在 try 后添加括号,把需要关闭的IO流类的实例化语句写在括号中即可。如下代码所示:

    try (//IO类实例化语句;(当有多个实例化语句时,最后一个不需要加分号)
    ) {
        //具体的IO执行业务逻辑;
    } catch (Exception e) {
        //异常处理;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这就是 try-with-resource 语句的格式。由于 FileReaderFileWriter 均实现了 java.lang.AutoCloseable 接口,因此,写在try 后面的括号中的IO对象在任意情况下均能被关闭。

    【例子】使用 try-with-resource 语句优化上面提到的代码:

    @Test
    public void testIO() {
        //1.创建File类的对象,指明读入和写出到的文件
        File srcFile = new File("hello.txt");
        File destFile = new File("hello1.txt");
    
        try (
                //2.创建输入流和输出流的对象
            	//使用了try-with-resource语句,在任意情况下都能被关闭
                FileReader fr = new FileReader(srcFile);
                FileWriter fw = new FileWriter(destFile)
        ) {
            //3.数据的读入和写出操作
            char[] cbuf = new char[(int) srcFile.length()];
            int len;//记录每次读入到cbuf数组中的字符的个数
            while ((len = fr.read(cbuf)) != -1) {
                //每次写出len个字符
                fw.write(cbuf, 0, len);
            }
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    由于不需要写 finally 代码块中的手动关闭资源代码,与未优化的代码 (43行) 相比,使用 try-with-resource 语句的代码简化到 25 行。

    3.注意事项

    • 【使用条件】要求该对象的类实现了 java.lang.AutoCloseable 接口 或 java.lang.Closeable 接口,才可以使用try-with-resource语句。(IO相关的类都实现的都是 java.lang.Closeable 接口。而 java.lang.Closeable 接口继承了 java.lang.AutoCloseable 接口,所以是满足条件的。)

    • try-with-resources语句可以像普通的try语句一样有catch和finally。在try-with-resources语句中,任何catch或finally块都是在声明的资源关闭后才被执行。

  • 相关阅读:
    函数指针、函数指针数组、计算器+转移表等归纳总结
    受欢迎的奶牛
    如何进行机器学习
    Pygame中Sprite的使用方法6-5
    vue3 动态组件
    几何距离与函数距离:解锁数据空间中的奥秘
    使用 swiper 轮播 echarts 图表,地图点击失效
    2022“杭电杯”中国大学生算法设计超级联赛(4)签到题5题
    【HMS core】【FAQ】典型问题合集7
    Shel简介入门
  • 原文地址:https://blog.csdn.net/Sihang_Xie/article/details/125463574