Does a finally block always get executed in Java?
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");
}
Solution 1:
Yes, finally
will be called after the execution of the try
or catch
code blocks.
The only times finally
won't be called are:
- If you invoke
System.exit()
- If you invoke
Runtime.getRuntime().halt(exitStatus)
- If the JVM crashes first
- If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the
try
orcatch
block - If the OS forcibly terminates the JVM process; e.g.,
kill -9 <pid>
on UNIX - If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
- If the
finally
block is going to be executed by a daemon thread and all other non-daemon threads exit beforefinally
is called
Solution 2:
Example code:
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("something is printed");
}
}
Output:
something is printed.
0