Created
July 6, 2017 04:20
-
-
Save megascus/100d2f04e4d063e4ad3c524adb9ea9d5 to your computer and use it in GitHub Desktop.
AutoCloseableの実行順序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
デコンパイル結果(上と同等なソースコードかつ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
stdout
new CloseableTest
throwException()
close()
catch exception
java.lang.Exception: surpressed