Java finally block and throws exception at method level
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
}
}
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.
No, it's completely unnecessary to catch an exception if you're not going to do anything other than throw it.
And yes, the finally block will still be executed.
No, it isn't necessary to catch the exception unless you can't rethrow it in your method. In the code you posted the readFileMethod2 is the correct option to follow.
the finally always get executed in try catch context ... for more info check http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html
finally is executed always irrespective of whether an exception is thrown or not. Only if the JVM is shut down while executing the try block or catch block, then the finally clause will not be executed. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
精彩评论