Categories

Tags

Meta

Java Suppressed Exceptions

Today I learned something new about Java exceptions. The always surprising try-catch statement has a concept called suppressed exceptions. The main idea is that a the whole try structure can throw an exception from more than one place:

The catch block

The finally block

The try-with-resources implicit close

The problem is this: methods can only throw one exception in the end. So, what happens to the other thrown exceptions? The catch block can rethrow its exception, the finally can throw a new one and the close can cause an IOException all in the same call. We can read the Java Language Specification (JLS) to figure it out, but first an experiment.

Do you know without running the example what the console will print?
–
–
–
–
It prints “In the finally”. This will be the first surprise. If you print some tracing messages throughout the code you’ll see that all three exceptions are thrown. First the one inside the try, then the one in the implicit close of the stream (suppressed), then the one in the catch block, and at last the one in the finally block. But this is about suppressed exceptions, like the one in the catch block. So now let’s try this:

Let's get a suppressed exception

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

publicstaticvoidmain(String[]args)throwsException{

try{

whichException();

}catch(Exceptione){

System.out.println(e);

for(Throwable suppressed:e.getSuppressed()){

System.out.println(suppressed);

}

System.out.println(e.getCause());

}

}

publicstaticvoidwhichException(){

try(OutputStream out=newBrokenOutputStream()){

thrownewIllegalArgumentException("In the try");

}catch(Exception ex){

thrownewIllegalArgumentException("In the catch",ex);

}finally{

// throw new IllegalArgumentException("In the finally");

}

}

The change comments out the exception in the finally and links the one thrown in the catch clause with the original. Now we can retrieve those suppressed exceptions from the exception that results from the whichException() method. If the try-with-resources block has multiple resources, each implicit close can throw its own exception. That’s why getSuppressed() returns an array.

I take two lessons from this exploration. First, do not throw or return from a finally clause. Second, a catch clause in a try-with-resources should consider the suppressed exceptions when reacting or logging. :>