Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 708
gigadot Avatar asked Jun 30 '11 17:06

gigadot


People also ask

Can we throw exception in finally block in Java?

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.

What will happen if an exception is thrown from the finally block in Java?

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.

Will finally block execute after throw exception?

A finally block always executes, regardless of whether an exception is thrown.

Does finally run even if I throw in catch?

The finally block executes regardless of whether an exception is thrown or caught.


1 Answers

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.

like image 81
Nathan Hughes Avatar answered Oct 16 '22 05:10

Nathan Hughes