推荐使用try-with-resources语句,Java 7引入该语法,自动关闭实现AutoCloseable接口的资源,确保无论是否异常都能正确释放,代码更简洁安全;若无法使用,应在finally块中对每个资源单独捕获关闭异常;也可通过工具类如IOUtils.closeQuietly封装关闭逻辑,避免资源泄漏。最有效方式为try-with-resources。

在Java中,finally块常用于释放资源,比如关闭文件流、数据库连接等。但若处理不当,可能出现资源未正确关闭的问题。为避免这种情况,可以采取以下几种有效方式。
使用try-with-resources语句
Java 7引入了try-with-resources语法,自动管理实现了AutoCloseable接口的资源。无论是否抛出异常,资源都会被自动关闭。
- 将资源声明在try后的括号中,JVM会确保其自动调用close()方法
- 无需手动编写finally块,代码更简洁且不易出错
示例:
try (FileInputStream fis = new FileInputStream("data.txt");
BufferedInputStream bis = new BufferedInputStream(fis)) {
int data;
while ((data = bis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.err.println("读取文件出错:" + e.getMessage());
}
// 资源在此自动关闭,无需finally
在finally中正确处理关闭逻辑
如果无法使用try-with-resources(如旧版本Java),在finally中关闭资源时需注意异常处理。
立即学习“Java免费学习笔记(深入)”;
- 关闭操作本身可能抛出异常,应将其捕获,避免掩盖主异常
- 对每个资源单独try-catch,防止一个关闭失败影响其他资源
示例:
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream("data.txt");
bis = new BufferedInputStream(fis);
// 使用资源...
} catch (IOException e) {
System.err.println("发生异常:" + e.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
System.err.println("关闭bis失败:" + e.getMessage());
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.err.println("关闭fis失败:" + e.getMessage());
}
}
}
优先使用工具类或封装方法
对于重复的资源关闭逻辑,可封装成工具方法,减少出错概率。
- Apache Commons IO提供了IOUtils.closeQuietly()等便捷方法
- 自定义close方法统一处理null判断和异常捕获
例如:
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// 静默处理或记录日志
}
}
}
基本上就这些。最推荐的方式是使用try-with-resources,它从根本上解决了finally中资源未关闭的问题,代码更安全也更清晰。










