Does finally always execute in Java?
I have a try/catch block with returns inside it. Will the finally block be called?
For example:
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("i don't know if this will get printed out.");
}
I know I can just type this in an see what happens (which is what I'm about to do, actually) but when I googled for answers nothing came up, so I figured I'd throw this up as a question.
Solution:
finally
will be called.
The only times
finally
won't be called are:- if you call
System.exit()
or - if the JVM crashes first
- if there is an infinite loop in the try block
- if the power turns off
http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java