Code inside a finally
block can throw an exception. Programmers often fail to catch and handle such exceptions. This can be problematic for several reasons. An exception thrown in a finally
block becomes the reason for abrupt termination of the entire try block, potentially masking an exception thrown in the try block. Further, the transfer of control associated with the exception prevents execution of any clean-up statements that follow the statement from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions thrown from within a finally
block.
Noncompliant Code Example
This noncompliant code example uses 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 handle the exception appropriately.
public class Operation { private static void doOperation(String some_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { reader.close(); // ... Other clean-up code ... } } public static void main(String[] args) throws IOException { String path = "somepath"; doOperation(path); } }
The close()
method could throw an IOException
, which would prevent execution of any subsequent clean-up 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()
.
Compliant Solution (Handle Exceptions in finally
Block)
This compliant solution correctly places the close()
statement in a try-catch
block of its own. Consequently, an IOException
can be handled without permitting it to propagate farther.
public class Operation { static void doOperation(String some_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { try { // Enclose in try-catch block reader.close(); } catch (IOException ie) { // Forward to handler } // Other clean-up code } } public static void main(String[] args) throws IOException { String path = "somepath"; doOperation(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.
public class Operation { static void doOperation(String some_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { closeHandlingException(reader); // Other clean-up code } } private static void closeHandlingException(BufferredReader s) { if (s != null) { try { s.close(); } catch (IOException ie) { // 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 (Java 1.7: try-with-resources)
Java 1.7 provides new syntax, dubbed try-with-resources, that can close certain resources automatically should an error occur. This compliant solution uses try-with-resources to properly close the file
public class Operation { static void doOperation(String some_file) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(some_file))) { // Do operations } } public static void main(String[] args) { try { doOperation(path); } catch (IOException ex) { System.out.println("thrown exception: " + ex.toString()); Throwable[] suppressed = ex.getSuppressed(); for (int i = 0; i < suppressed.length; i++) { System.out.println("suppressed exception: " + suppressed[i].toString()); } } } }
If an error occurs in the try block (the // Do operations
section), it will propagate out of doOperation
, and be printed as the "thrown exception". If an error occurs while closing the reader
, that error will propagate out of doOperation
, and be printed as the "thrown exception". But 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". In all cases the reader
is safely closed.
Risk Assessment
Failure to handle an exception in a finally
block can lead to unexpected results.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXC05-J |
low |
unlikely |
medium |
P2 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
[[Bloch 2005]] Puzzle 41: Field and Stream
[[Chess 2007]] 8.3 Preventing Resource Leaks (Java)
[[Harold 1999]]
[[J2SE 2011]] The try-with-resources Statement
ERR04-J. Do not exit abruptly from a finally block 06. Exceptional Behavior (ERR) ERR06-J. Do not allow exceptions to expose sensitive information