java - Closeable 和 AutoCloseable close() 方法的执行顺序
问题描述
有人可以向我解释这里发生了什么以及按什么顺序吗?输出对我来说没有任何意义。
输出为 T 1 IOE F。
代码是:
import java.io.Closeable;
import java.io.IOException;
public class TestRes {
public static void main(String[] args) {
try (
MyResource11 r1 = new MyResource11();
MyResource21 r2 = new MyResource21();
)
{
System.out.print("T ");
} catch (IOException ioe) {
System.out.print("IOE ");
} finally {
System.out.print("F ");
}
}
}
class MyResource11 implements AutoCloseable {
public void close() throws IOException {
System.out.print("1 ");
}
}
class MyResource21 implements Closeable {
public void close() throws IOException {
throw new IOException();
}
}
解决方案
try-with-resources 以与声明它们的顺序相反的顺序关闭资源。所以代码:
- 印刷
T
- try-with-resources 语句试图关闭
r2
- 这会引发异常
- try-with-resources 语句成功关闭
r1
,输出1
- 运行异常块(对于来自 的异常
r2
)并输出IOE
- finally 块运行,输出
F
值得阅读JLS 的 try-with-resources 部分,其中包括未解开的 try-with-resources 语句的代码示例(例如,仅带有try
/ catch
/的等效代码finally
)。从那个部分:
资源以与它们初始化时相反的顺序关闭。仅当资源初始化为非空值时才关闭资源。关闭一个资源的异常不会阻止关闭其他资源。如果异常之前由初始化程序、try 块或资源关闭引发,则此类异常将被抑制。
推荐阅读
- c++ - 如何更新 WinAPI ListView 中特定项目的特定子项目?
- flutter - 使用 Riverpod 进行状态管理
- bash - grep 所有至少包含 X 个单词的行
- ruby - 将参数传递给 Ruby 方法
- macos - 如何在 mac 上的 odoo 14 中配置自定义插件路径?
- r - 在 R 中有一列具有 205550 个值,并且想要 10 列,其中值 1 进入第 1 列,值 2 进入第 2 列等
- python - 如何在 django 中创建一个传入多个对象的字典的自定义模板标签
- rmi - RMI 中的存根和 RPC 中的存根有什么区别?
- sql - 将带有信息的 Varchar 拆分为表格
- unity3d - 如何在不使用 public 的情况下编写脚本?