目录
- Java try()语句实现try-with-resources异常管理机制操作
- 不使用try-with-resources时,使用的资源要在finally中进行释放
- 使用try-with-resources时
- 自定义AutoCloseable实现
- try-with-resources语句优雅的关闭资源
- 在java1.7以前,我们关闭资源的方式如下
- 我们先直接上一个demo,方便理解
- 反编译之后我们可以看见
- 源码里面有解释
- 总结一下吧
Java try()语句实现try-with-resources异常管理机制
Java 7 引入了 try-with-resources 语法特性,允许在 try 语句块中声明并管理资源。当代码块执行完毕(无论是否发生异常),系统会自动调用资源的 close 方法进行清理,无需开发者手动干预,其便捷性类似于 Python 中的 with...as 语句。
要利用这一特性,相关类必须实现 java.lang.AutoCloseable 接口。该接口仅包含一个 close() 方法,用于定义资源释放的具体逻辑。
public interface AutoCloseable{
public void close() throws Exception;
}
Java 标准库中的所有 IO 流均实现了 AutoCloseable 接口,因此可以直接在 try() 括号内实例化并使用。此外,用户自定义的类只要遵循此接口规范,同样可以享受自动资源管理的便利。
在不使用 try-with-resources 的传统模式下,必须在 finally 代码块中显式编写资源释放逻辑。
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
File f = new File("d:/test.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally 里关闭流
if (null != fis)
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
使用 try-with-resources 时
其语法结构为 try(...),括号内部可以包含一个或多个资源初始化语句,各语句之间以分号分隔。
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
File f = new File("d:/lol.txt");
//把流定义在try()里,try,catch或者finally结束的时候,会自动关闭
try (FileInputStream fis = new FileInputStream(f)) {
byte[] all = new byte[(int) f.length()];
fis.read(all);
for (byte b : all) {
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
自定义AutoCloseable实现
在 TestAutoCloseable 类的 close 方法中添加打印语句,以便观察资源关闭时的执行情况。
package test;
public class TestAutoCloseable implements AutoCloseable{
public TestAutoCloseable() {
System.out.println("class TestAutoCloceable");
}
public void close() {
System.out.println("function close() executed");
}
}
测试代码
package test;
public class TestFeature {
public static void main(String[] args) {
// TODO Auto-generated method stub
try(TestAutoCloseable testAutoCloseable = new TestAutoCloseable()){
}
}
}
运行结果显示,即使未在代码中显式调用,close 方法依然被自动触发执行。

try-with-resources语句优雅的关闭资源
在 Java 开发中,若打开了文件、数据库连接或网络套接字等外部资源,务必在使用完毕后及时关闭。
由于这些外部资源不受 JVM 垃圾回收机制管辖,若未能确保在正确时机释放,将引发资源泄露。这可能导致文件句柄被异常占用、数据库连接池耗尽等严重故障。
在 java1.7以前,我们关闭资源的方式如下
public class CloseTest {
public static void main(String[] args){
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("file.txt");
fileInputStream.read();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
为保证资源绝对被关闭,传统做法是将关闭逻辑置于 finally 块中。鉴于 close() 方法可能抛出 IOException,经典的防御性编程模板应运而生。
然而,自 java1.7 版本起,新增了 try-with-resources 这一语法糖,极大地简化了上述繁琐过程。
我们先直接上一个demo,方便理解
public class CloseTest {
public static void main(String[] args) {
try (FileInputStream fileInputStream1 = new FileInputStream("file1.txt");
FileInputStream fileInputStream2 = new FileInputStream("file2.txt")) {
fileInputStream1.read();
fileInputStream2.read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
将资源句柄的创建置于 try 关键字后的括号内。一旦 try-catch 代码块执行结束,Java 虚拟机保证会调用外部资源的 close 方法。若涉及多个资源,需使用分号进行隔离。
反编译之后我们可以看见
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream(new File("test"));
Throwable var2 = null;
try {
System.out.println(inputStream.read());
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (inputStream != null) {
if (var2 != null) {
try {
inputStream.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
}
} else {
inputStream.close();
}
}
}
} catch (IOException var14) {
throw new RuntimeException(var14.getMessage(), var14);
}
}
通过查看反编译后的字节码,可以发现其中包含一处对异常的特殊处理逻辑:
var2.addSuppressed(var11);
这涉及 try-with-resources 的另一核心概念——异常抑制。当对外部资源进行操作(如读写)发生异常,且在随后的资源关闭过程中又产生新异常时,catch 块捕获的将是原始操作异常。关闭阶段产生的异常会被“抑制”而非丢弃,可通过异常的 getSuppressed() 方法提取这些被抑制的异常信息。
源码里面有解释
/**
* Returns an array containing all of the exceptions that were
* suppressed, typically by the {@code try}-with-resources
* statement, in order to deliver this exception.
*
* If no exceptions were suppressed or {@linkplain
* #Throwable(String, Throwable, boolean, boolean) suppression is
* disabled}, an empty array is returned. This method is
* thread-safe. Writes to the returned array do not affect future
* calls to this method.
*
* @return an array containing all of the exceptions that were
* suppressed to deliver this exception.
* @since 1.7
*/
public final synchronized Throwable[] getSuppressed() {
if (suppressedExceptions == SUPPRESSED_SENTINEL ||
suppressedExceptions == null)
return EMPTY_THROWABLE_ARRAY;
else
return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
}
总结一下吧
综上所述,无论程序执行路径如何(正常结束或抛出异常),资源都必须得到释放。在 JDK 1.6 及更早版本中,应将 close() 放入 finally 块以确保安全;而在 JDK 1.7 及以上版本中,强烈推荐使用 try-with-resources 语句。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。