I’m trying to understand how the new try-with-resources statement works by recreating it using regular try-catch-finally statements. Given the following test class using Java 7 try-with-resources:
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class TryWithResources {
public static void main(String[] args) {
try (GZIPOutputStream gzip = new GZIPOutputStream(System.out)) {
gzip.write("TEST".getBytes("UTF-8"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
How would you rewrite this class to use try-catch-finally statements which produces exactly the same bytecode as the try-with-resources statement produces? Also, same question when two resources are used, as in the following example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class TryWithResources2 {
public static void main(String[] args) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
gzip.write("TEST".getBytes("UTF-8"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
For the
TryWithResourcesclass, the following class produces equivalent bytecode as the try-with-resources:Using Sun JDK 1.7.0, the bytecode and exception tables for the main method in both
TryWithResourcesandTryCatchFinallyclasses is:For the
TryWithResources2class, the following class produces equivalent bytecode as the try-with-resources:The bytecode and exception tables for the main method in both
TryWithResources2andTryCatchFinally2classes is: