LoginSignup
4

More than 5 years have passed since last update.

try-with-resources構文でfinally句を書くとどうなる?

Posted at

ふとした疑問。try-with-resources構文でfinally句を書くとどうなるのか。
もちろん、try句で指定したCloseable(AutoCloseable)#closeが呼ばれて、finally句も呼ばれることを期待。

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");
        }
    }

}

結果

try
close
finally

ちゃんと期待通りになってる。(そりゃそうか)
デコンパイルするとこんな感じ。

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");
        }
    }
}

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
4