Sudden question. What happens if you write a finally clause in the try-with-resources syntax? Of course, expect that Closeable (AutoCloseable) #close specified in the try clause will be called, and finally clause will also be called.
Main.java
public class Main {
public static void main(String[] args) throws Exception {
try (Hoge hoge = new Hoge()) {
System.out.println("try");
} finally {
System.out.println("finally");
}
}
public static class Hoge implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("close");
}
}
}
result
try
close
finally
It's exactly what I expected. (That's right) When decompiled, it looks like this.
Main.java
public class Main2 {
public static void main(String[] args) throws Throwable {
try {
Throwable arg0 = null;
Object arg1 = null;
try {
Main.Hoge hoge = new Main.Hoge();
try {
System.out.println("try");
} finally {
if (hoge != null) {
hoge.close();
}
}
} catch (Throwable arg14) {
if (arg0 == null) {
arg0 = arg14;
} else if (arg0 != arg14) {
arg0.addSuppressed(arg14);
}
throw arg0;
}
} finally {
System.out.println("finally");
}
}
public static class Hoge implements AutoCloseable {
public void close() throws Exception {
System.out.println("close");
}
}
}
Recommended Posts