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 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 {
doSomething();
System.out.println("yikes! don't program like this!");
} 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 {
return;
}
}
}
2 comments:
Good description of the phenomenon: http://www.javaworld.com/javaworld/jw-02-1997/jw-02-hood.html?page=1
Greeat share
Post a Comment