Java 异常处理之 try-with-resources

2023-08-31  本文已影响0人  Tinyspot

1. 基础

1.1 定义多个 resources

@Test
public void test() {
    try {
        // 1.加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");

        // 2.获得数据库的连接
        Connection connection = DriverManager.getConnection(URL, NAME, PASSWORD);

        // 3.通过数据库的连接操作数据库,实现增删改查
        Statement statement = connection.createStatement();

        ResultSet resultSet = statement.executeQuery("select name,age from tb_user");

        // 循环打印数据
        while (resultSet.next()) {
            System.out.println(resultSet.getString("name") + "," + resultSet.getInt("age"));
        }
        
        // 4. 关闭连接,释放资源 (按创建顺序倒序进行关闭)
        resultSet.close();
        statement.close();
        connection.close();
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

改为 try-with-resources

@Test
public void test() {
    try (Connection connection = DriverManager.getConnection(url, user, password);
         Statement statement = connection.createStatement();
         ResultSet resultSet = statement.executeQuery("SELECT ...")) {
        // ...
    } catch (Exception e) {
        // ...
    }
}

如果在 try 中定义了多个 resources,它们关闭的顺序和创建的顺序是相反的
上面的例子中,依次创建了 Connection、Statment、ResultSet 对象,最终关闭时会依次关闭 ResultSet、Statment、Connection

2. Replacing try-catch-finally With try-with-resources

2.1 try-catch-finally

@Test
public void readFile() {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("src/main/resources/user.json"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        // 异常日志
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
BufferedReader.png

2.2 try-with-resources

@Test
public void readFileTry() {
    try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/user.json"))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        // 异常日志
    }
}

3. 自定义自动关闭类

public class MyAutoCloseable implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("资源关闭...");
    }
}

测试正常情况

@Test
public void test() {
    try (MyAutoCloseable autoCloseable = new MyAutoCloseable()) {
        System.out.println("无异常");
    } catch (Exception e) {
        System.out.println("出现异常:" + e.getClass());
    }
}

测试异常情况

@Test
public void test() {
    try (MyAutoCloseable autoCloseable = new MyAutoCloseable()) {
        System.out.println("测试异常:");
        String str = null;
        System.out.println(str.equals("111"));
    } catch (Exception e) {
        System.out.println("出现异常:" + e.getClass());
    }
}
上一篇 下一篇

猜你喜欢

热点阅读