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. This 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 finally
block.
Allowing checked exceptions to escape a finally
block also violates rule ERR04-J. Do not exit 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.
Code Block | ||
---|---|---|
| ||
public class Operation { public static void doOperation(String some_file) { // ... codeCode to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { reader.close(); // ... Other cleanup code ... } } catch (IOException x) { // Forward to handler } } } |
The close()
method can throw an IOException
, which, if thrown, would prevent execution of any subsequent cleanup statements. This is a problem that 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.
...
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.
Code Block | ||
---|---|---|
| ||
public class Operation { public static void doOperation(String some_file) { // ... codeCode to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { try { reader.close(); } catch (IOException ie) { // Forward to handler } // ... Other clean-upcleanup code ... } } catch (IOException x) { // Forward to handler } } } |
Compliant Solution (
...
try
-with-resources)
Java SE 7 introduced a new feature , called try
-with-resources, that that can close certain resources automatically in the event of an error. This compliant solution uses try
-with-resources to properly close the file.
Code Block | ||
---|---|---|
| ||
public class Operation { public static void doOperation(String some_file) { // ... codeCode to check or set character encoding ... try ( // try-with-resources BufferedReader reader = new BufferedReader(new FileReader(some_file))) { // Do operations } catch (IOException ex) { System.err.println("thrown exception: " + ex.toString()); Throwable[] suppressed = ex.getSuppressed(); for (int i = 0; i < suppressed.length; i++) { System.err.println("suppressed exception: " + suppressed[i].toString()); } // Forward to handler } } public static void main(String[] args) { if (args.length < 1) { System.out.println("Please supply a path as an argument"); return; } doOperation(args[0]); } } |
When an IOException
occurs in the try
block of the doOperation()
method, it is caught by the catch
block and printed as the thrown exception. This includes exceptions 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 IOException
, the 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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR05-J |
Low |
Unlikely |
Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Coverity | 7.5 | PW.ABNORMAL_TERMINATION_ OF_FINALLY_BLOCK | Implemented | ||||||
Parasoft Jtest |
| CERT.ERR05.ARCF CERT.ERR05.ATSF | Avoid using 'return's inside 'finally blocks if thare are other 'return's inside the try-catch block Do not exit "finally" blocks abruptly | ||||||
SonarQube |
| S1163 | Exceptions should not be thrown in finally blocks |
Related Guidelines
248, Uncaught Exception CWE-460, Improper Cleanup on Thrown Exception |
, Return inside |
CWE-705. Incorrect control flow scoping
Bibliography
Bibliography
Puzzle 41, "Field and Stream" | |
Section 8.3, "Preventing Resource Leaks (Java)" | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c488d039-01b9-4764-a7af-d29b41d21717"><ac:plain-text-body><![CDATA[
[[Bloch 2005
AA. References#Bloch 05]]
Puzzle 41. Field and Stream
]]></ac:plain-text-body></ac:structured-macro>
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="a83f0d8e-7a57-4bcb-be2d-644ba8e7e25b"><ac:plain-text-body><![CDATA[
[[Chess 2007
AA. References#Chess 07]]
8.3, Preventing Resource Leaks (Java)
]]></ac:plain-text-body></ac:structured-macro>
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="daa09659-a367-4192-b284-a8945ae98726"><ac:plain-text-body><![CDATA[
[[Harold 1999
AA. References#Harold 99]]
]]></ac:plain-text-body></ac:structured-macro>
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="37f6a9fd-2309-4b00-b7a0-188a06b19377"><ac:plain-text-body><![CDATA[
[[J2SE 2011
The |
]]></ac:plain-text-body></ac:structured-macro>
...
ERR04-J. Do not exit abruptly from a finally block 06. Exceptional Behavior (ERR)