compiled class problem in java try/catch block

Vikram R :

I have try and catch block in JAVA code

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();
        }

    }

}

And my compiled class look like

/* * Decompiled with CFR 0.145. */ ....

try {
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(string));){
        String string2 = "Hello";
        System.out.println("==============>" + string2);
    }

....

I wounder why another try block added in compile time.

Full Source code in

https://github.com/vikram06/java_try_catch_bug

Arnaud :

This is explained in the 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=124470&siteId=1