Code inside Methods invoked from within a finally
block can throw an exception. Programmers often fail Failing to catch and handle such exceptions . This can be problematic for several reasons. An exception thrown in a finally
block becomes the reason for results in the abrupt termination of the entire try
block, potentially masking an any exception thrown in the try
block. FurtherAdditionally, the transfer of control associated with the exception prevents execution of any clean-up statements that follow the statement expressions or statement that occurs after the point in the finally
block from which the exception is thrown. Consequently, programs must appropriately handle checked exceptions thrown from within a finally
block.
...
Code Block | ||
---|---|---|
| ||
public class Operation { private static void doOperation(String some_file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { reader.close(); // ... Other clean-up code ... } } public static void main(String[] args) throws IOException { String path = "somepath"; doOperation(path); } } |
The close()
method could can throw an IOException
, which would prevent execution of any subsequent clean-up statements. This possibility remains undiagnosed at compile time because the close()
method's throws clause specifies the same exceptions as do the throws clauses of methods read()
and write()
.
...