Returning from a finally block in Java

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.

Leave a Comment