debugjavaCritical
Does a finally block always get executed in Java?
Viewed 0 times
javaexecutedblockdoesalwaysfinallyget
Problem
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
Yes,
The only times
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
tryorcatchblock
- If the OS forcibly terminates the JVM process; e.g.,
kill -9on UNIX
- If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
- If the
finallyblock is going to be executed by a daemon thread and all other non-daemon threads exit beforefinallyis called
Context
Stack Overflow Q#65035, score: 3037
Revisions (0)
No revisions yet.