Mukund Gandlur Mukund Gandlur - 4 months ago 32
Java Question

Suppressed exceptions in Java

Consider the below example.

public static void main(String[] args) {

throw new NullPointerException();
} finally{
throw new ClassCastException();


This throws a ClassCastException only and the NullPointerException is suppressed. And this is possible in Java SE6 too. Then why are Suppressed Exceptions stressed upon only in JavaSE7. What is it that I am missing here?


How is it different from this? Isn't it just 2 exceptions thrown with the latest one suppressing the previous one.

What you are actually doing is better described as "replacing" on exception with another. (Or more precisely, thrown the second exception unconditionally!)

Exception suppression (as the JLS uses the term) is different in the following respects:

  1. Normal suppression happens (automatically) only to exceptions that are thrown in a try-with-resources, during resource cleanup by the try-with-resources. What you are doing in your example happens to any / all exceptions, irrespective of their origin.

  2. With normal suppression, the secondary exception is suppressed. In this case the primary exception is being "suppressed".

  3. With normal suppression, the suppressed exception is recorded in the original exception. In your example, it is discarded.

Now, admittedly, you could use the Throwable.addSuppressedException(...) method by hand in other ways. I'm describing how it is intended to be used.