Methods invoked from within a finally
block can throw an exception. Failing Failure to catch and handle such exceptions results in the abrupt termination of the entire try
block, suppressing . 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 prevents may prevent execution of any expressions or statement statements that occurs 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 ERR04-J. Do not complete abruptly from a finally block.
Noncompliant Code Example
This noncompliant code example uses 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 the any exception appropriatelythat may arise.
Code Block | ||
---|---|---|
| ||
public class Operation { privatepublic static void doOperation(String some_file) throws IOException { // ... Code to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { reader.close(); // ... Other clean-upcleanup code ... } } public static} voidcatch main(String[]IOException argsx) throws{ IOException { String// pathForward = "somepath";to handler doOperation(path);} } } |
The close()
method can throw an IOException
, which, if thrown, would prevent execution of any subsequent clean-up cleanup statements. This possibility remains undiagnosed at compile time because the close()
method's throws clause specifies the same exceptions as do the throws clauses of methods read()
and write()
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 finally
Block)
This compliant solution correctly places encloses the close()
statement method invocation in a try-catch
block of its own within the finally
block. Consequently, an the potential IOException
can be handled without permitting allowing it to propagate fartherfurther.
Code Block | ||
---|---|---|
| ||
public class Operation { public static void doOperation(String some_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { ... Code to check or set character encoding ... try { BufferedReader reader //= Enclose in try-catch block new reader.close()BufferedReader(new FileReader(some_file)); } catch (IOException ie) try { // ForwardDo tooperations handler } // Other clean-up code } } public static void main(String[] args) throws IOExceptionfinally { try { String path = "somepath"; doOperationreader.close(path); } } |
While suppressing a caught exception normally violates ERR00-J. Do not suppress or ignore checked exceptions, this particular code would likelybe allowed under ERR00-EX0, as the reader
would never be accessed again, so an error in closing it can not affect future program behavior.
Compliant Solution (Dedicated Method to Handle Exceptions)
When closing a stream without throwing an exception is a frequent pattern in the code, an alternative solution is to use a closeHandlingException()
method, as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
public class Operation { static void doOperation(String some_file) throws IOException } catch (IOException ie) { BufferedReader reader = new BufferedReader(new FileReader(some_file)); // Forward tryto {handler // Do operations } finally { closeHandlingException(reader); // ... Other clean-upcleanup code ... } } private static void closeHandlingException(BufferredReader s) { if (s != null) { try { s.close(); } catch (IOException iex) { // Forward to handler } } } public static void main(String[] args) throws IOException { doOperation("somepath"); } } |
While suppressing a caught exception normally violates ERR00-J. Do not suppress or ignore checked exceptions, this particular code would be allowed under ERR00-EX0, as the reader
would never be accessed again, so an error in closing it can not affect future program behavior.
Compliant Solution (
...
try
-with-resources)
Java 1.7 provides new syntax, dubbed SE 7 introduced a feature called try
-with-resources, that that can close certain resources automatically should in the event of an error occur. This compliant solution uses try
-with-resources to properly close the file.
Code Block | ||
---|---|---|
| ||
public class Operation { public static void doOperation(String some_file) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(some_file))) {// ... Code to check or set character encoding ... try ( // Do operations try-with-resources } BufferedReader }reader = public static void main(String[] args) { new tryBufferedReader(new FileReader(some_file))) { // Do doOperation(path);operations } catch (IOException ex) { System.outerr.println("thrown exception: " + ex.toString()); Throwable[] suppressed = ex.getSuppressed(); for (int i = 0; i < suppressed.length; i++) { System.outerr.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]); } } |
If When an error IOException
occurs in the try
block (the Do operations
section), it will propagate out of doOperation
, and be of the doOperation()
method, it is caught by the catch
block and printed as the "thrown exception". If an error . Exceptions that occur while creating the BufferedReader
are included. When an IOException
occurs while closing the reader
, that error will propagate out of doOperation
, and be exception is also caught by the catch
block and printed as the " thrown exception". But if If both errors occur, the try
- block error will be the one that propagates out of doOperation
, and be printed as the "thrown exception". The close error gets suppressed, and will be printed as the "supprssed exception"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.
Note that this example is for illustrative purposes only. Compliant code will do proper exception handling, rather than simply printing exceptions to the console. For more information, see ERR00-J. Do not suppress or ignore checked exceptions.
Risk Assessment
Failure to handle an exception in a finally
block can lead to may have unexpected results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|
ERR05-J |
Low |
Unlikely |
Medium | P2 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
Wiki Markup |
---|
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 41: Field and Stream
\[[Chess 2007|AA. Bibliography#Chess 07]\] 8.3 Preventing Resource Leaks (Java)
\[[Harold 1999|AA. Bibliography#Harold 99]\]
\[[J2SE 2011|AA. Bibliography#J2SE 11]\] The try-with-resources Statement |
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
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 |
Bibliography
Puzzle 41, "Field and Stream" | |
Section 8.3, "Preventing Resource Leaks (Java)" | |
The |
...
ERR04-J. Do not exit abruptly from a finally block 06. Exceptional Behavior (ERR) ERR06-J. Do not allow exceptions to expose sensitive information