Imagine a situation where, an exception occurs in try with resources block. It will call the close method to close the resources. What happens if close method also throws an exception. Which exception is thrown.?
1 Answer
The answer is: Both! The first one is just a bit more prominent.
First your inner exception will be thrown. Then the close() method of the Closeable will be called and if that one does also throw its exception, it will be suppressed by the first one. You can see that in the stack trace.
Test code:
public class DemoApplication { public static void main(String[] args) throws IOException { try (Test test = new Test()) { throw new RuntimeException("RuntimeException"); } } private static class Test implements Closeable { @Override public void close() throws IOException { throw new IOException("IOException"); } } } Console log:
Exception in thread "main" java.lang.RuntimeException: RuntimeException at DemoApplication.main(DemoApplication.java:15) Suppressed: java.io.IOException: IOException at DemoApplication$Test.close(DemoApplication.java:22) at DemoApplication.main(DemoApplication.java:16) If you like to, you can get the suppressed exception with exception.getSuppressed().
3 Comments
Stephen C
Your description has it the wrong way around, it is the second exception (i.e. the one thrown by the
close operation) that will be suppressed. As shown by the stacktrace!Sabari Dheera
The description given was right as it is said that the Exception thrown by the close method is suppressed.
Ed MacDonald
What happens if ONLY close() throws an exception?
[try-with-resources]which you used in your question explains it…