Java8でtry-with-resourcesを試してみました

@さんの記事Java7 体当たり/try-with-resources Statement - 日々常々を写経。
JavaSE8のJavaDocでAutoCloseableを見ていると@FunctionalInterfaceになっているので、Lambdaを使って写経してみました。

  • version

  • 正常終了した場合(close1、close2とも実行されていました)
public class TryWithResources{
    public static void main(String... args) {
        try (AutoCloseable c1 = () -> System.out.println("close1");
             AutoCloseable c2 = () -> System.out.println("close2");
             AutoCloseable c3 = null;) {
          System.out.println("new");
        } catch (Exception e){
          System.out.println("catch:" + e);
        } finally {
          System.out.println("finally");
        }
    }
} 
  • 実施結果

  • 異常終了した場合
public class TryWithResources2 {
    public static void main(String... args) {
      try (AutoCloseable c1 = () -> { 
            System.out.println("close1");
            int i = Integer.parseInt("err1");
            };
           AutoCloseable c2 = () -> {
            System.out.println("close2");
            int i = Integer.parseInt("err2");
            };
           AutoCloseable c3 = null;) {
        System.out.println("new");
      } catch (Exception e){
        System.out.println("catch:" + e);
        for (Throwable t : e.getSuppressed()) {
            System.out.println("suppressed:" + t);
        }
      } finally {
        System.out.println("finally");
    }
    }
} 
  • 実施結果

ちょっとしたことですが、Lambda式で書けると便利ですよね。