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();
}
}
}
阅读 1125 · 发布于 2022-04-26
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓
昵称:
-
fHLvlxbf 1楼
e
Chrome | Windows 10 2023-07-24
随便看看
换一批
-
PHP 使用 Zend OPcache 字节码缓存阅读 2605
-
CentOS7 安装 Docker阅读 3637
-
JavaFX TextArea 按 Enter 键发送阅读 2037
-
macOS OpenSSL 生成 p12 证书阅读 124
-
minikube 导入本地 Docker 镜像阅读 1352
-
Git 提示 error failed to push some refs to git@github.com阅读 3237
-
JavaScript 获取 img 图片的绝对路径和相对路径阅读 275
-
Vue v-cloak 解决页面闪烁阅读 712
-
Python 内置函数阅读 1556
-
软考-系统架构设计师:信息与信息化的概念阅读 1182