Java: Suppressed Exceptions

Suppressed exceptions were introduced at the same time as the try-with-resource feature. This is because in a try-with-resource two exceptions may be thrown (one from the try block and one from the implicit call to close()), and since a method can throw at most one exception, the other exception must be suppressed.

Suppressed exceptions can be used manually as well. To add an exception as suppressed by another exception, you call Throwable.addSuppressed. To retrieve the suppressed exceptions you call Throwable.getSuppressed.

Example: Adding and retrieving suppressed exceptions.

Exception exc = new Exception();
exc.addSuppressed(new Exception("Sup. 1"));
exc.addSuppressed(new Exception("Sup. 2"));

System.out.println(Arrays.toString(exc.getSuppressed()));

Output:

[java.lang.Exception: Suppressed 1, java.lang.Exception: Suppressed 2]

Stack traces includes suppressed exceptions, similarly to how they print "caused by" exceptions.

Example: exc.printStackTrace() would in the previous example print:

java.lang.Exception
        at Example.main(Example.java:5)
        Suppressed: java.lang.Exception: Sup. 1
                at Example.main(Example.java:6)
        Suppressed: java.lang.Exception: Sup. 2
                at Example.main(Example.java:7)
Suppressed exceptions should not be confused with chained exceptions, also known as wrapped exceptions. See article on Chained Exceptions for details.

Comments

Be the first to comment!