What javac does
try-with-resources
close() on every path, and addSuppressed when close() fails too.
try-with-resources expands into the code you would otherwise write by hand: a close() on the normal path, and a handler for any Throwable that closes the resource, attaches any exception from close() to the first one with addSuppressed, and rethrows the first.
The source
// try-with-resources: close() on every path, and suppressed exceptions.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryResources {
static String firstLine(String path) throws IOException {
try (BufferedReader in = new BufferedReader(new FileReader(path))) {
return in.readLine();
}
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
close()appears twice: afterreadLine()returns normally, and in the handler.- If
close()throws while an exception is already on its way out, the inner handler callsaddSuppressed, so the original exception is the one that propagates. - There is no null check before
close()because the resource is anewexpression, which cannot be null. A resource returned by a method call gets anifnulltest before eachclose(). - javac 25 generates this code the same way for every
--release: the flag changes the class file version and the APIs you may call, not how the statement is compiled.
TryResources.class
static String firstLine(String path)
javac --release 8 to 25 (the same bytecode for every release)
| From | To | Handler | Catches |
|---|---|---|---|
| 16 | 21 | 27 | java.lang.Throwable |
| 28 | 32 | 35 | java.lang.Throwable |