...
Code Block | ||
---|---|---|
| ||
public class Operation { private static void doOperation(String some_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(some_file)); // Do operations try { // Do operations } finally { reader.close(); // ... 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 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
Code Block | ||
---|---|---|
| ||
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.
...