java中try-with-resources可自动关闭autocloseable资源,避免手动close和资源泄漏;需实现autocloseable接口,声明时用分号分隔,关闭顺序与声明相反,支持抑制异常获取及自定义资源实现。

Java 中使用 try-with-resources 可以自动关闭实现了 AutoCloseable 接口的资源(如文件流、数据库连接等),避免手动调用 close(),减少资源泄漏风险。
资源必须实现 AutoCloseable 接口
只有实现了 AutoCloseable(或其子接口 Closeable)的类才能用于 try-with-resources。常见如:
-
FileInputStream/FileOutputStream -
BufferedReader/BufferedWriter Scanner-
Connection、Statement、ResultSet(JDBC)
基本语法:在 try 后括号中声明资源
资源在 try 括号内声明并初始化,会在 try 块结束(无论是否异常)时自动调用 close():
try (FileInputStream fis = new FileInputStream("data.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis))) {
String line = reader.readLine();
System.out.println(line);
} // ← 这里自动调用 reader.close() 和 fis.close()
注意:多个资源用分号分隔,关闭顺序与声明顺序相反(后声明的先关闭),符合依赖关系逻辑。
Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设...
异常处理:抑制异常(Suppressed Exception)
如果 try 块抛出异常,且 close() 也抛出异常,后者会被“抑制”,并可通过 Throwable.getSuppressed() 获取:
try (FileInputStream fis = new FileInputStream("missing.txt")) {
// 抛出 FileNotFoundException
} catch (IOException e) {
System.out.println("主异常: " + e.getMessage());
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("被抑制的异常: " + suppressed.getMessage());
}
}
自定义资源:让类支持 try-with-resources
只需让类实现 AutoCloseable 并重写 close() 方法:
class MyResource implements AutoCloseable {
public void doSomething() {
System.out.println("正在操作资源");
}
@Override
public void close() {
System.out.println("资源已释放");
}
}
// 使用:
try (MyResource res = new MyResource()) {
res.doSomething();
} // ← 自动调用 close()
不复杂但容易忽略:确保资源是 final 或 effectively final(不能在 try 块内重新赋值),否则编译报错。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










