You can see from this article that the finally clause is executed properly when you return in the try clause of Try-Catch-Finally.
About return in try-catch-finally clause
I doubt here. Will Try-with-Resources, which is very similar in Java, close resources properly? I actually checked it.
https://github.com/takeo-asai/try-with-resources
public class Main {
public static void main(String[] args) {
System.out.println("Begin Main");
tryWithResources();
System.out.println("End Main");
}
private static void tryWithResources() {
try (MockConnection connection = new MockConnection();) {
System.out.println("tryWithResources");
return;
}
}
}
public class MockConnection implements AutoCloseable {
public void close() {
System.out.println("MockConnection is closed.");
}
}
Begin Main
tryWithResources
MockConnection is closed.
End Main
In conclusion, it will close properly, so let's use it hard.
Recommended Posts