《Effective Java》解读第9条:try-with-resources 优先于 try-finally
文章目录
- 第9条:try-with-resources 优先于 try-finally
- 优势对比
- 总结
第9条:try-with-resources 优先于 try-finally
绝对优先使用 try-with-resources,完全淘汰 try-finally 用于资源管理。
优势对比
- 代码简洁性
// ❌ 传统方式 - 繁琐易错
InputStream in = null;
try {in = new FileInputStream("file.txt");// 使用资源
} finally {if (in != null) {try {in.close();} catch (IOException e) {// 处理关闭异常}}
}// ✅ 现代方式 - 简洁安全
try (InputStream in = new FileInputStream("file.txt")) {// 使用资源
} // 自动关闭,无需finally块
- 异常处理
// ❌ try-finally:后发生的异常会覆盖先发生的异常
try {throw new RuntimeException("业务异常");
} finally {throw new RuntimeException("关闭异常"); // 这个会覆盖上面的异常!
}// ✅ try-with-resources:保留所有异常信息
try (ProblemResource res = new ProblemResource()) {throw new RuntimeException("业务异常");
}
// 两个异常都会保留,业务异常为主异常,关闭异常被抑制
- 使用条件
// 所有标准库资源都支持
try (InputStream in = new FileInputStream("file");OutputStream out = new FileOutputStream("file2");Connection conn = DriverManager.getConnection(url);PreparedStatement stmt = conn.prepareStatement(sql)) {// 业务逻辑
}
- 多资源自动管理
// 多个资源自动按创建顺序的逆序关闭
try (FileInputStream input = new FileInputStream("source");FileOutputStream output = new FileOutputStream("target");ZipOutputStream zip = new ZipOutputStream(output)) {// 先关闭 zip,然后 output,最后 input
}
- 自定义资源实现
public class MyResource implements AutoCloseable{@Overridepublic void close() throws Exception {// 释放资源}public static void main(String[] args) {try (MyResource resource = new MyResource()) {// 使用资源} catch (Exception e) {// 处理异常}}
}
总结
代码更简洁:减少样板代码,提高可读性
异常更完整:不会丢失原始异常信息
资源更安全:自动关闭,避免资源泄漏
顺序更智能:自动逆序关闭多个资源
调试更容易:完整的异常链便于问题定位
只有在必须处理 非 AutoCloseable 资源 时才考虑 try-finally,但这种场景极少。
