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.");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With