In readFileMethod1
, an IOException
is explicitly catched before throwing it at the method level to ensure that the finally
block is executed. However, is it neccessary to catch the exception? If I remove the catch block, shown in readFileMethod2
, does the finally
block get executed as well?
private void readFileMethod1() throws IOException {
try {
// do some IO stuff
} catch (IOException ex) {
throw ex;
} finally {
// release resources
}
}
private void readFileMethod2() throws IOException {
try {
// do some IO stuff
} finally {
// release resources
}
}
Methods invoked from within a finally block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire try block.
The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.
A finally block always executes, regardless of whether an exception is thrown.
The finally block executes regardless of whether an exception is thrown or caught.
The finally
still gets executed, regardless of whether you catch the IOException. If all your catch block does is rethrow, then it is not necessary here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With