Skip to main content

Don't return in a finally clause

Posted by staufferjames on June 27, 2007 at 9:46 AM PDT

The code below actually prints "yikes!"

If you return in a finally block then any Throwables that aren't caught (in a catch block that is part of the same try statement as the finally block) will be completely lost. The really bad part about this is that it looks so innocent. I can think of no reason to return in a finally clause. If nothing else, catch(Throwable t) and return in that so it is obvious what is happening. Note this also applies to other things that transfer control (continue, throw, etc).

public class Test {

  public static void main(String[] args) {
    try {
    } catch (RuntimeException e) {
      System.out.println("got it.");
  public static void doSomething() {
    try {
      //Normally you would have code that doesn't explicitly appear
      //to throw exceptions so it would be harder to see the problem.
      throw new RuntimeException();
    } finally {
Related Topics >>