Methods invoked from within a finally
block can throw an exception. Failing Failure to catch and handle such exceptions results in the abrupt termination of the entire try
block. This causes any exception thrown in the try
block to be forgotten, 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 statement statements that occurs occur after the point in the finally
block from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions appropriately that are thrown from within a finally
block.
...
This noncompliant code example contains 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 appropriately handle the any exception appropriatelythat may arise.
Code Block | ||
---|---|---|
| ||
public class Operation {
private static void doOperation(String some_file) throws IOException {
BufferedReader reader = null;
// ... code to check or set character encoding ...
try {
reader = new BufferedReader(new FileReader(some_file));
// Do operations
} finally {
if (reader != null) {
reader.close();
}
// ... Other clean-up code ...
}
}
public static void main(String[] args) throws IOException {
String path = "somepath";
doOperation(path);
}
}
|
The close()
method can throw an IOException
which, if thrown, would prevent execution of any subsequent clean-up statements. The compiler will not correctly fail to diagnose this problem because the doOperation()
method explicitly declares that it may throw IOException
.
...
This compliant solution encloses the close()
method invocation in a try-catch
block of its own within the finally
block. Consequently, an the potential IOException
can be handled without permitting it to propagate farther.
Code Block | ||
---|---|---|
| ||
public class Operation {
static void doOperation(String some_file) throws IOException {
BufferedReader reader = null;
// ... code to check or set character encoding ...
try {
reader = new BufferedReader(new FileReader(some_file));
// Do operations
} finally {
if (reader != null) {
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 ignoring a caught exception normally violates ERR00-J. Do not suppress or ignore checked exceptions, this particular code is permitted under ERR00-EX0, as the reader
is never accessed again, so an error in closing it does not affect leaves future program behavior unchanged.
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 of a closeHandlingException()
method, as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
public class Operation {
static void doOperation(String some_file) throws IOException {
BufferedReader reader = null;
// ... code to check or set character encoding ...
try {
reader = new BufferedReader(new FileReader(some_file));
// 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");
}
}
|
...
Java 1.7 provides a new feature, called try-with-resources, that can close certain resources automatically should in the event of 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) {
// ... code to check or set character encoding ...
try (BufferedReader reader = new BufferedReader(new FileReader(some_file))) {
// Do operations
} catch (IOException ex) {
System.err.println("thrown exception: " + ex.toString());
Throwable[] suppressed = ex.getSuppressed();
for (int i = 0; i < suppressed.length; i++) {
System.err.println("suppressed exception: " + suppressed[i].toString());
}
// Handle exception
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please supply a path as an argument");
return;
}
doOperation(args[0]);
}
}
|
If When an IOException
occurs in the try
block of the doOperation()
method it will be caught by the catch block and be printed as the thrown exception. This includes both any error while doing operations as well as and also any error incurred while creating the BufferedReader
. If When an IOException
occurs while closing the reader
, that error will also be caught by the catch block and will be printed as the thrown exception. If IOException}}s occur in When both the try block and while also closing the {{reader
throw an IOException
, the catch clause still catches both exceptions, and prints the try-block error as the thrown exception. The close error is suppressed and printed as the suppressed exception. In all cases the reader
is safely closed.
For this program not to violate This example as written violates ERR00-J. Do not suppress or ignore checked exceptions, ; the appropriate error handling must be addedrequired for compliance has been elided for clarity.
Risk Assessment
Failure to handle an exception in a finally
block can lead to unexpected results.
...