java - java try/catch 块中的编译类问题
问题描述
我尝试在 JAVA 代码中捕获块
import java.io.FileOutputStream;
import java.util.zip.ZipOutputStream;
public class TryTest {
public static void main(String[] args) {
String zipPath ="D:/test";
try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))){
String Hello ="Hello";
System.out.println("==============>"+Hello);
}catch (Exception e) {
e.printStackTrace();
}
}
}
我编译的类看起来像
/* * 使用 CFR 0.145 反编译。*/ ....
try {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(string));){
String string2 = "Hello";
System.out.println("==============>" + string2);
}
……
我很奇怪为什么在编译时添加了另一个 try 块。
完整的源代码在
解决方案
这在 JLS 14.20.3.2 Extended try-with-resources中有解释:
扩展的 try-with-resources 语句的含义:
try ResourceSpecification
Block
Catchesopt
Finallyopt
通过以下对嵌套在 try-catch 或 try-finally 或 try-catch-finally 语句中的基本 try-with-resources 语句(第 14.20.3.1 节)的翻译给出:
try {
try ResourceSpecification
Block
}
Catchesopt
Finallyopt
翻译的效果是将 ResourceSpecification 放在 try 语句的“内部”。这允许扩展的 try-with-resources 语句的 catch 子句捕获由于任何资源的自动初始化或关闭而导致的异常。
此外,在执行 finally 块时,所有资源都将关闭(或试图关闭),这与 finally 关键字的意图保持一致。
推荐阅读
- swift - View on View 控制器在 Xcode 11 上都是方形的,怎么样?
- qliksense - 如何在 Qlik Sense 中默认显示最近一周的交易量
- javascript - 如何在 javscript/node 中导入对象
- python - Python 如何处理子包?
- vba - 选择单元格时创建文件夹和子文件夹
- vue.js - 你如何在 firebase 服务工作者和 Vue/Vuex 网络应用程序之间进行通信
- xamarin - 如何在 Xamarin.iOS 中使用 Google 的人员 API?
- python - 为什么“5 in range(5,6) in [range(5,6)]”返回True?
- java - java rest 调用获取 url net::ERR_FAILED
- php - 在 PHP 中删除和创建 MySQL 视图不起作用