Java – Returning from a finally block in Java

exceptionjavareturntry-catch-finally

I was surprised recently to find that it's possible to have a return statement in a finally block in Java.

It seems like lots of people think it's a bad thing to do as described in 'Don't return in a finally clause'. Scratching a little deeper, I also found 'Java's return doesn't always' which shows some pretty horrible examples of other types of flow control in finally blocks.

So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?

Best Answer

I had a REALLY hard time to track down a bug years ago that was caused by this. The code was something like:

Object problemMethod() {
    Object rtn = null;
    try {
        rtn = somethingThatThrewAnException();
    }
    finally {
        doSomeCleanup();
        return rtn;
    }
}

What happened is that the exception was thrown down in some other code. It was being caught and logged and rethrown within the somethingThatThrewAnException() method. But the exception wasn't being propagated up past problemMethod(). After a LONG time of looking at this we finally tracked it down to the return method. The return method in the finally block was basically stopping the exception that happened in the try block from propagating up even though it wasn't caught.

Like others have said, while it is legal to return from a finally block according to the Java spec, it is a BAD thing and shouldn't be done.