1. 基础
- 官方文档传送门
https://docs.oracle.com/javase/8/docs/technotes/guides/language/try-with-resources.html
- 从 Java7 引入 try-with-resources
- 需要实现 AutoCloseable 接口
- 实现 Closeable 也可以
interface Closeable extends AutoCloseable
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();
}
}
}

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());
}
}
网友评论