try-with-resources 和 try-catch-finally 有什么区别
try-with-resources 是 java 7 引入的语法糖,专门用于自动管理实现了 autocloseable 接口的资源,它会自动调用 close() 方法并处理异常。而传统的 try-catch-finally 需要开发者手动在 finally 块中编写逻辑来关闭资源,且容易因空指针或重复关闭导致错误。使用 try-with-resources 代码更简洁、安全,推荐作为首选方案。

传统 try-catch-finally 的资源管理痛点
在传统写法中,如果需要在 finally 块中关闭多个资源,必须逐个检查是否为空,并且要捕获 IOException 以防止关闭操作本身抛出异常掩盖主逻辑中的异常。这种写法冗长且容易出错。

import java.io.*;
public class TraditionalTry {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
int data = fis.read();
System.out.println("Read: " + data);
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.err.println("Close Error: " + e.getMessage());
}
}
}
}
}
try-with-resources 的优势与实现
try-with-resources 允许在 try 语句括号内声明资源,这些资源会在 try 块结束时自动关闭。它支持多资源声明,用分号分隔,关闭顺序与声明顺序相反。此外,它还能更好地处理异常链,保留原始异常而非被关闭异常覆盖。
Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。
立即学习“Java免费学习笔记(深入)”;

import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("test.txt")) {
int data = fis.read();
System.out.println("Read: " + data);
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
}
}
}
当资源关闭时抛出异常会发生什么
如果使用 try-with-resources 且资源关闭时抛出异常,该异常会被抑制(Suppressed),原始异常仍会向上传播。可以通过 getSuppressed() 方法获取所有被抑制的异常。而在传统 finally 中,如果关闭操作抛出异常,它会直接替换掉 try 块中抛出的异常,导致原始异常丢失。

















