Considering this code, can I be absolutely sure that the finally
block always executes, no matter what something()
is?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("i don't know if this will get printed out.");
}
I tried the above example with slight modification-
The above code outputs:
This is because when
return i;
is executedi
has a value 2. After this thefinally
block is executed where 12 is assigned toi
and thenSystem.out
out is executed.After executing the
finally
block thetry
block returns 2, rather than returning 12, because this return statement is not executed again.If you will debug this code in Eclipse then you'll get a feeling that after executing
System.out
offinally
block thereturn
statement oftry
block is executed again. But this is not the case. It simply returns the value 2.If an exception is thrown, finally runs. If an exception is not thrown, finally runs. If the exception is caught, finally runs. If the exception is not caught, finally runs.
Only time it does not run is when JVM exits.
Because the final is always be called in whatever cases you have. You don't have exception, it is still called, catch exception, it is still called
In addition to the other responses, it is important to point out that 'finally' has the right to override any exception/returned value by the try..catch block. For example, the following code returns 12:
Similarly, the following method does not throw an exception:
While the following method does throw it:
Also a return in finally will throw away any exception. http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html
Because a finally block will always be called unless you call
System.exit()
(or the thread crashes).