Throwing an exception from within a finally block will mask any exception which was previously thrown in the try
or catch
block, and the masked’s exception message and stack trace will be lost.
Noncompliant Code Example
try {
/* some work which end up throwing an exception */
throw new IllegalArgumentException();
} finally {
/* clean up */
throw new RuntimeException(); // Noncompliant; masks the IllegalArgumentException
}
Compliant Solution
try {
/* some work which end up throwing an exception */
throw new IllegalArgumentException();
} finally {
/* clean up */
}
See
- CERT, ERR05-J. - Do not let checked exceptions escape from a finally block