Considering this code, can I be absolutely sure that the finally
block always executes, no matter what something()
is?
try
Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:
try { return true; } finally { return false; }
Same thing with throwing exceptions from the finally block.
Also a return in finally will throw away any exception. http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html
In addition to the point about return in finally replacing a return in the try block, the same is true of an exception. A finally block that throws an exception will replace a return or exception thrown from within the try block.
Yes It will. Only case it will not is JVM exits or crashes
Here's an elaboration of Kevin's answer. It's important to know that the expression to be returned is evaluated before finally
, even if it is returned after.
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int printX() {
System.out.println("X");
return 0;
}
public static int test() {
try {
return printX();
}
finally {
System.out.println("finally trumps return... sort of");
}
}
Output:
X
finally trumps return... sort of
0
finally
is always executed and before returning x
's (calculated) value.
System.out.println(foo());
....
int foo(){
int x = 2;
try{
return x++;
} finally{
System.out.println(x);
}
}
Output:
3
2