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 finally
block.
Allowing checked exceptions to escape a finally
block also violates ERR04-J. Do not complete abruptly from a finally blockAn exception can occur in the finally
block despite compile-time checking. This can prevent other clean-up statements from being executed.
Noncompliant Code Example
The finally
clause This noncompliant code example contains a finally
block that closes the reader
object in this noncompliant code example. However, it is incorrectly assumed . The programmer incorrectly assumes that the statements within in the finally
block cannot throw exceptions . Notably, the close()
method can throw an IOException
which prevents any subsequent clean-up lines from being executed. This is not detected at compile time as the type of exception that close()
throws is the same as the ones that read
and write
throwand consequently fails to appropriately handle any exception that may arise.
Code Block | ||
---|---|---|
| ||
public class LoginOperation { public static void checkPassworddoOperation(String passwordsome_file) throws IOException { // ... Code to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(passwordsome_file)); // Compare credentialstry { // Do operations } finally { reader.close(); // ... Other clean-upcleanup code ... } } public static} voidcatch main(String[]IOException argsx) throws{ IOException { String// pathForward = "password";to handler checkPassword(path);} } } |
The 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 finally
Block)
This compliant solution correctly places encloses the close()
statement method invocation in a try-catch
block . As a result, an of its own within the finally
block. Consequently, the potential IOException
can be handled without letting allowing it to propagate any further.
Code Block | ||
---|---|---|
| ||
public class LoginOperation { public static void checkPassworddoOperation(String passwordsome_file) throws IOException { // ... Code to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(passwordsome_file)); try { // CompareDo operations credentials } finally { try { // Enclose in try-catch block reader.close(); } catch (IOException ie) { // Forward to handler } // ... Other clean-upcleanup code ... } } public static} voidcatch main(String[]IOException argsx) throws{ IOException { String// pathForward = "password";to handler checkPassword(path);} } } |
Compliant Solution (
...
try
-with-resources)
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 fileIf the need to close a stream without throwing an exception occurs often, then an alternative solution to wrapping every call of close()
in its own try-catch
block is, to write a closeIgnoringException()
method as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
public class LoginOperation { public static void checkPassworddoOperation(String passwordsome_file) throws IOException { { // ... Code to check or set character encoding ... try ( // try-with-resources BufferedReader reader = new BufferedReader(new FileReader(passwordsome_file))); try { // CompareDo credentialsoperations } finallycatch (IOException ex) { closeIgnoringException(readerSystem.err.println("thrown exception: " + ex.toString()); Throwable[] suppressed // Other clean-up code } } private static void closeIgnoringException(BufferredReader s) { if (s != null) {= ex.getSuppressed(); for (int i = 0; i < suppressed.length; i++) { System.err.println("suppressed exception: " try { s.close(+ suppressed[i].toString()); } catch (IOException ie) { // IgnoreForward exception if close fails to handler } } } public static void main(String[] args) throws IOException{ if (args.length < 1) { System.out.println("Please supply Stringa path =as an "password"argument"); return; checkPassword(path} doOperation(args[0]); } } |
In production systems, it is often better to limit the lifetime of sensitive data by avoiding the use of a BufferedReader
. See the guideline MSC08-J. Limit the lifetime of sensitive data for more detailsWhen an 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 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.
Risk Assessment
Failing 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 |
Automated Detection
...
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[Bloch 05|AA. Java References#Bloch 05]\] Puzzle 41: Field and Stream
\[[Harold 99|AA. Java References#Harold 99]\]
\[[Chess 07|AA. Java References#Chess 07]\] 8.3 Preventing Resource Leaks (Java) |
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 |
...
EXC30-J. Do not exit abruptly from a finally block 13. Exceptional Behavior (EXC) EXC32-J. Catch specific exceptions as opposed to the more general RuntimeException