HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaCritical

Does a finally block always get executed in Java?

Submitted by: @import:stackoverflow-api··
0
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, 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 or catch block



  • If the OS forcibly terminates the JVM process; e.g., kill -9 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 before finally is called

Context

Stack Overflow Q#65035, score: 3037

Revisions (0)

No revisions yet.