1

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

1 Answer 1

3

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().

Sign up to request clarification or add additional context in comments.

3 Comments

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!
The description given was right as it is said that the Exception thrown by the close method is suppressed.
What happens if ONLY close() throws an exception?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.