gpt4 book ai didi

java - Java try/catch block 中的编译类问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:11:17 26 4
gpt4 key购买 nike

我在 JAVA 代码中有 try 和 catch block

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 block 。

完整源代码在

https://github.com/vikram06/java_try_catch_bug

最佳答案

这在 JLS 14.20.3.2 Extended try-with-resources 中有解释:

The meaning of an extended try-with-resources statement:

try ResourceSpecification
Block
Catchesopt
Finallyopt

is given by the following translation to a basic try-with-resources statement (§14.20.3.1) nested inside a try-catch or try-finally or try-catch-finally statement:

try {
try ResourceSpecification
Block
}
Catchesopt
Finallyopt

The effect of the translation is to put the ResourceSpecification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

关于java - Java try/catch block 中的编译类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com