Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are exceptions thrown in a finally block added to the list of suppressed exceptions?

Java 7 added the concept of suppressed exceptions. The try-with-resource statement adds exceptions that are thrown by a resource's close() method to the list of suppressed exceptions, if they occur when another exception is already propagating up the stack.

Does the same happen for exceptions thrown in a try statement's finally block, like in the following example?

try {
    throw new RuntimeException("Exception in try block.");
} finally {
    throw new RuntimeException("Exception in finally block.");
}
like image 631
Feuermurmel Avatar asked Oct 25 '13 07:10

Feuermurmel


1 Answers

No. The idea of suppressed exceptions is that they are happening in the implicit finally in try with resources. If you have actually coded your own finally block, exceptions thrown in it are not treated as suppressed exceptions. Note that if you have both a try with resources and your own finally block, the try with resources close() exceptions are still suppressed and your own finally block's are treated as regular exceptions.

As a way to remember this, Java strives for backward compatibility. This means exceptions in finally block you coded work the same way they always have. Only the implicit finally of try with resources generates the new suppressed exceptions.

like image 177
Jeanne Boyarsky Avatar answered Oct 20 '22 02:10

Jeanne Boyarsky