javaexceptionreturntry-catch-finally

Returning from a finally block in Java


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?


Solution

  • 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....