...
Notably, the close()
method can throw an IOException
which prevents any subsequent clean-up statements from being executed. This is not detected at compile time because the type of exception that close()
throws is the same as the type of exceptions that methods read()
and write()
throw.
Compliant Solution (1) (handle exceptions in finally
block)
This compliant solution correctly places the close()
statement in a try-catch
block. As a result, an IOException
can be handled without letting it propagate any further.
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); } } |
Compliant Solution (2) (dedicated method to handle exceptions)
If there is a frequent need to close a stream without throwing an exception, an alternative solution to wrapping every call to close()
in its own try-catch
block is to use a closeIgnoringException()
method, as shown in this compliant solution.
...