try-catch-finally和try-with-resources

Java开发超实用100篇:https://blog.csdn.net/libusi001/article/details/100086670

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

一、老版代码

@Test
public void test4() {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream("D:\\head.jpg");
        // do something
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、新写法

@Test
public void test5() {
    try (InputStream inputStream = new FileInputStream("D:\\head.jpg")) {
        byte[] bytes = inputStream.readAllBytes();
        // do something
    } catch (IOException e) {
        e.printStackTrace();
    }
}

try-with-resources的用法就是,在try关键字的后面跟一个括号,把需要关闭的资源定义在括号内。在try块执行完之后会自动的释放掉资源。

有用请点赞,养成良好习惯!

疑问、交流、鼓励请留言!

发布了267 篇原创文章 · 获赞 145 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/libusi001/article/details/103992047