What's the output of the following code?
class Box implements AutoCloseable { public void open() throws Exception { throw new Exception(); }/* w w w . j a v a 2 s . co m*/ public void close() throws Exception { System.out.println("close"); throw new Exception(); } } class Main { public static void main(String args[]) { try (Box box = new Box()) { box.open(); } catch (Exception e) { System.out.println("catch:" + e); } finally { System.out.println("finally"); } } }
a catch:java.lang.Exception finally// w w w. j av a 2s . c o m b catch:java.lang.Exception c close finally d close catch:java.lang.Exception finally e close catch:java.lang.Exception catch:java.lang.Exception finally
d
The code box.open()
within the try block throws an Exception.
Before the control is transferred to the exception handler, the resource box is implicitly closed by calling its close()
method, which also throws an Exception.
If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed.
So the exception thrown by the implicit call to box.close()
is suppressed.
A suppressed exception forms the cause of the exception that suppresses it.
It can be retrieved by using method getSuppressed()
on the exception handler, as follows:.
catch (Exception e) { System.out.println("catch:"+e); for (Throwable th : e.getSuppressed()) System.out.println(th); }
It prints the following:.
catch:java.lang.Exception
java.lang.Exception