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

There are 1 best solutions below

3
On

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