 |
Don't return in a finally clause
Posted by staufferjames on June 27, 2007 at 09:46 AM | Comments (7)
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 {
doSomething();
System.out.println("yikes!");
} 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;
}
}
}
Bookmark blog post: del.icio.us Digg DZone Furl Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment
-
You can even set this to be a compiler error in Eclipse if you want.
Preferences > Java > Compiler > Errors / Warnings > Potential Programming Problems > 'finally' does not complete normally, set it to "Error".
Posted by: neilf79 on September 13, 2007 at 09:34 AM
-
Why not just disable this feature? Are there any relevant use cases where you would want to return from a finally?
Posted by: drunken_wizard on July 01, 2007 at 11:10 PM
-
hi there,
I've been bitten by this. Because the code looks so innocent, I had to scratch my head. For a while, I thought that the java interpreter was buggy. I was lazy to look up the JLS at that time(4 years ago).
BR,
~A
Posted by: anjanb2 on June 29, 2007 at 01:07 PM
-
Eclipse IDE says that the finally block does not complete normally.
Posted by: dlinsin on June 28, 2007 at 10:42 PM
-
The JLS says that this is allowed.
Note the phrase "either no finally block is present or the finally block can complete normally" at
http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#11.2.2
Posted by: staufferjames on June 28, 2007 at 04:18 PM
-
Hmm.. sounds like returning in a finally clause should be forbidden by the language!!
I never thought of doing this.. scary.
Posted by: dog on June 28, 2007 at 04:11 PM
-
Is this part of the language spec? Is a finally with a return supposed to override the Exception?
Posted by: m0smith on June 28, 2007 at 03:13 PM
|