Returning from a finally block in Java

前端 未结 6 1921
醉梦人生
醉梦人生 2020-11-22 11:02

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 d

6条回答
  •  粉色の甜心
    2020-11-22 11:49

    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.

提交回复
热议问题