LoginSignup
7
5

More than 5 years have passed since last update.

Java の Try-with-Resources で、try句中に return してもちゃんと close されるから気にせず return しよう

Posted at

Try-Catch-Finally は問題ない

Try-Catch-Finally の try句中で return した場合、ちゃんと finally句が実行されることはこちらの記事から確認できる。

try-catch-finally句内のreturnについて

Try-with-Resources で実際に確認してみた

ここで疑問。Java でよく似た Try-with-Resources ではきちんとリソースを close してくれるのだろうか?
実際に確認してみた。

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

結論としてはちゃんと close してくれるので、ガンガン使っていこう。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5