Methods invoked from within a
finally block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire
try block. Abrupt termination causes any exception thrown in the
try block to be lost, preventing any possible recovery method from handling that specific problem. Additionally, the transfer of control associated with the exception may prevent execution of any expressions or statements that occur after the point in the
finally block from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions that are thrown from within a
Allowing checked exceptions to escape a
finally block also violates ERR04-J. Do not complete abruptly from a finally block.
Noncompliant Code Example
This noncompliant code example contains a
finally block that closes the
reader object. The programmer incorrectly assumes that the statements in the
finally block cannot throw exceptions and consequently fails to appropriately handle any exception that may arise.
close() method can throw an
IOException, which, if thrown, would prevent execution of any subsequent cleanup statements. This problem will not be diagnosed by the compiler because any
IOException would be caught by the outer
catch block. Also, an exception thrown from the
close() operation can mask any exception that gets thrown during execution of the
Do operations block, preventing proper recovery.
Compliant Solution (Handle Exceptions in
This compliant solution encloses the
close() method invocation in a
try-catch block of its own within the
finally block. Consequently, the potential
IOException can be handled without allowing it to propagate further.
Compliant Solution (
Java SE 7 introduced a feature called
try-with-resources that can close certain resources automatically in the event of an error. This compliant solution uses
try-with-resources to properly close the file.
IOException occurs in the
try block of the
doOperation() method, it is caught by the
catch block and printed as the thrown exception. Exceptions that occur while creating the
BufferedReader are included. When an
IOException occurs while closing the
reader, that exception is also caught by the
catch block and printed as the thrown exception. If both the
try block and closing the
reader throw an
catch clause catches both exceptions and prints the
try block exception as the thrown exception. The close exception is suppressed and printed as the suppressed exception. In all cases, the
reader is safely closed.
Failure to handle an exception in a
finally block may have unexpected results.
|S1163||Exceptions should not be thrown in finally blocks|
CWE-248, Uncaught Exception
CWE-460, Improper Cleanup on Thrown Exception
CWE-584, Return inside
CWE-705, Incorrect Control Flow Scoping
CWE-754, Improper Check for Unusual or Exceptional Conditions
Puzzle 41, "Field and Stream"
Section 8.3, "Preventing Resource Leaks (Java)"