首页 > 解决方案 > 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 块。

完整的源代码在

https://github.com/vikram06/java_try_catch_bug

标签: java

解决方案


这在 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 关键字的意图保持一致。


推荐阅读