...
Code Block | ||
---|---|---|
| ||
public class Operation { public static void doOperation(String some_file) { // ... Code 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 cleanup 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.
...
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
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 |
...
...