In Java Try-with-Resources, even if you return in the try clause, it will be closed properly, so let's return without worrying

Try-Catch-Finally is fine

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 actually checked it with Try-with-Resources

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

In Java Try-with-Resources, even if you return in the try clause, it will be closed properly, so let's return without worrying
I stumbled on the Java version in Android Studio, so I will summarize it
Be careful if you find SHIFT-JIS in Java
The Records that are preview released in JDK 14 are nice, so let's try it with JShell