...
| Code Block | ||
|---|---|---|
| ||
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.
| Code Block | ||
|---|---|---|
| ||
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) {
// IgnoreForward exception if close failsto 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.
Risk Assessment
Failure to handle an exception in a finally block can lead to unexpected results.
...