Skip to content

Instantly share code, notes, and snippets.

@megascus
Created July 6, 2017 04:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megascus/100d2f04e4d063e4ad3c524adb9ea9d5 to your computer and use it in GitHub Desktop.
Save megascus/100d2f04e4d063e4ad3c524adb9ea9d5 to your computer and use it in GitHub Desktop.
AutoCloseableの実行順序
public class CloseableTest implements AutoCloseable {
public static void main(String[] args) {
try (CloseableTest test = new CloseableTest()) {
test.throwException();;
} catch (Exception e) {
System.out.println("catch exception");
System.out.println(e.getSuppressed()[0]); //close()メソッドの中で投げられた例外にcatch句でアクセスができる。
}
}
CloseableTest() {
System.out.println("new CloseableTest");
}
void throwException() throws Exception {
System.out.println("throwException()");
throw new Exception();
}
@Override
public void close() throws Exception {
System.out.println("close()");
throw new Exception("surpressed");
}
}
@megascus
Copy link
Author

megascus commented Jul 6, 2017

stdout

new CloseableTest
throwException()
close()
catch exception
java.lang.Exception: surpressed

@megascus
Copy link
Author

megascus commented Jul 6, 2017

デコンパイル結果(上と同等なソースコードかつtry-with-resourcesを使わない場合)

import java.io.PrintStream;

public class CloseableTest
  implements AutoCloseable
{
  public static void main(String[] args)
  {
    try
    {
      CloseableTest test = new CloseableTest();Throwable localThrowable3 = null;
      try
      {
        test.throwException();
      }
      catch (Throwable localThrowable1)
      {
        localThrowable3 = localThrowable1;throw localThrowable1;
      }
      finally
      {
        if (test != null) {
          if (localThrowable3 != null) {
            try
            {
              test.close();
            }
            catch (Throwable localThrowable2)
            {
              localThrowable3.addSuppressed(localThrowable2);
            }
          } else {
            test.close();
          }
        }
      }
    }
    catch (Exception e)
    {
      System.out.println("catch exception");
      System.out.println(e.getSuppressed()[0]);
    }
  }
  
  CloseableTest()
  {
    System.out.println("new CloseableTest");
  }
  
  void throwException()
    throws Exception
  {
    System.out.println("throwException()");
    throw new Exception();
  }
  
  public void close()
    throws Exception
  {
    System.out.println("close()");
    throw new Exception("surpressed");
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment