Returning from a finally block in Java

javac will warn of return in finally if you use the -Xlint:finally. Originally javac emitted no warnings - if something is wrong with the code, it should fail to compile. Unfortunately backwards compatibility means that unanticipated ingenious foolishness cannot be prohibited.

Exceptions can be thrown from finally blocks, but in that case the exhibited behaviour is almost certainly what you want.


The examples you provided are reason enough to not use flow-control from finally.

Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you....


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.