Java 语法糖 - try with resource
Java 评论 1 大约 961 字前提
需要实现AutoCloseable
接口。
示例一
Java 代码
public class Test8 {
public static void main(String[] args) {
try (InputStream is = new FileInputStream("/a.txt")) {
System.out.println(is);
} catch (IOException e) {
e.printStackTrace();
}
}
}
反编译 class
可以看到:
如果出现异常后在catch
中再次进行try
来关闭流,如关闭流出现异常就追加到异常中,最后抛出异常。
如果没有异常则正常close
。
public class Test8 {
public Test8() {
}
public static void main(String[] args) {
try {
FileInputStream is = new FileInputStream("/a.txt");
try {
System.out.println(is);
} catch (Throwable var5) {
try {
is.close();
} catch (Throwable var4) {
var5.addSuppressed(var4);
}
throw var5;
}
is.close();
} catch (IOException var6) {
var6.printStackTrace();
}
}
}
阅读 1007 · 发布于 2022-04-26
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
-
fHLvlxbf 1楼
e
Chrome | Windows 10 2023-07-24
随便看看
换一批
-
OpenResty 使用 lua-resty-auto-ssl 配置 https 证书阅读 6124
-
PHP 设置 json_encode 不转义中文阅读 2116
-
Go go build 命令阅读 3178
-
PHP 判断函数、类、方法、属性、数组中的 key 是否存在阅读 3747
-
Linux 不排序去除重复行和不排序统计重复行阅读 5943
-
为什么匿名内部类引用外部局部变量必须要加 final 关键字阅读 821
-
Docker Compose 容器编排阅读 1111
-
为什么 Redis 的 hash slot 设置为 16384阅读 2592
-
IDEA 滚轮调节字体大小阅读 2645
-
Docker 搭建私有仓库 Registry阅读 1135