推荐使用 try-with-resources 或 try-catch-finally 处理异常并执行清理。try-with-resources 适用于 AutoCloseable 资源,如流操作,能自动关闭资源;示例中 FileInputStream 和 BufferedReader 在 try 括号内声明,自动调用 close()。对于未实现 AutoCloseable 的资源或需手动清理(如解锁),应使用 finally 块,确保代码始终执行;示例中 fis 在 finally 中安全关闭,避免资源泄漏。实际开发优先选用 try-with-resources,可结合 finally 执行额外逻辑,但通常无需。数据库连接示例展示了 Connection 和 PreparedStatement 的自动释放。合理选择机制提升代码安全性与简洁性。

在Java中,捕获异常的同时执行清理操作,推荐使用 try-with-resources 语句或结合 finally 块的 try-catch-finally 结构。这两种方式能确保无论是否发生异常,资源都能被正确释放或清理代码得以执行。
使用 try-with-resources 自动管理资源
try-with-resources 适用于实现了 AutoCloseable 接口的对象(如文件流、网络连接等)。在 try 块结束时,无论是否抛出异常,资源都会自动关闭。
- 资源声明在 try 后的括号中
- 多个资源可用分号隔开
- 系统自动调用 close() 方法
示例:
try (FileInputStream fis = new FileInputStream("data.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))) {
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e) {
System.err.println("读取文件出错:" + e.getMessage());
}
// fis 和 reader 已自动关闭
使用 finally 块执行必须的清理逻辑
当处理的资源未实现 AutoCloseable,或需要执行非资源释放的操作(如解锁、状态重置),可在 catch 后使用 finally 块。
立即学习“Java免费学习笔记(深入)”;
- finally 块始终执行,即使发生异常或 return 语句
- 适合手动释放资源或记录日志等操作
- 注意避免在 finally 中抛出异常覆盖原有异常
示例:
FileInputStream fis = null;
try {
fis = new FileInputStream("data.txt");
int data = fis.read();
while (data != -1) {
System.out.print((char) data);
data = fis.read();
}
} catch (IOException e) {
System.err.println("IO异常:" + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close(); // 确保关闭流
} catch (IOException e) {
System.err.println("关闭流失败:" + e.getMessage());
}
}
}
结合 try-catch-finally 与 try-with-resources
实际开发中,优先使用 try-with-resources。若需额外清理动作,可在此基础上添加 finally 块,但通常不必要,因为资源已自动处理。
例如,在数据库操作中:
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement(sql)) {
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// 处理结果
}
} catch (SQLException e) {
System.err.println("数据库操作失败:" + e.getMessage());
}
// 连接和语句自动关闭
基本上就这些。合理选择机制,能让异常处理更安全、代码更简洁。










