...
The finally
clause closes the reader
object in this noncompliant code example. However, it is incorrectly assumed that the statements within the finally
block cannot throw exceptions. Notably, the close()
method can throw an IOException
which prevents any subsequent clean-up lines from being executed. This is not detected at compile time as the type of exception that close()
throws is the same as the ones type of exceptions that the methods read()
and write()
throw.
Code Block | ||
---|---|---|
| ||
public class LoginOperation { static void checkPassworddoOperation(String passwordsome_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(passwordsome_file)); // CompareDo credentialsoperations } finally { reader.close(); // Other clean-up code } } public static void main(String[] args) throws IOException { String path = "passwordsomepath"; checkPassworddoOperation(path); } } |
Compliant Solution (1)
...
Code Block | ||
---|---|---|
| ||
public class LoginOperation { static void checkPassworddoOperation(String passwordsome_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(passwordsome_file)); try { // CompareDo credentialsoperations } 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 = "passwordsomepath"; checkPassworddoOperation(path); } } |
Compliant Solution (2)
If the there is a frequent need to close a stream without throwing an exception occurs often, then an alternative solution to wrapping every call of to close()
in its own try-catch
block is , to write use a closeIgnoringException()
method, as shown in this compliant solution.
Code Block | ||
---|---|---|
| ||
public class LoginOperation { static void checkPassworddoOperation(String passwordsome_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(passwordsome_file)); try { // CompareDo credentialsoperations } finally { closeIgnoringException(reader); // Other clean-up code } } private static void closeIgnoringException(BufferredReader s) { if (s != null) { try { s.close(); } catch (IOException ie) { // Ignore exception if close fails } } } public static void main(String[] args) throws IOException { String path = "passwordsomepath"; checkPassworddoOperation(path); } } |
...
Risk Assessment
Failing to handle an exception in a finally
block can lead to unexpected results.
...