Does a finally block always get executed in Java?
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
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