This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Is a finally block always executed in Java?

Given this code, can I be absolutely sure that the finally block is always executed, no matter what something() it is?

try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("I don't know if this will get printed out");
}
Copy the code

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Yes, finally will be called after a try or catch block is executed.

The only time finally is not called is when:

  • If you call system.exit ()

  • If you call Runtime.geTruntime ().halt(exitStatus)

  • If the JVM crashes first

  • If the JVM reaches an infinite loop (or other uninterrupted, non-terminating statement) in a try or catch block

  • Whether the operating system forcibly terminated the JVM process; For example, kill -9 on UNIX

  • If the host system crashes; For example, power failure, hardware error, operating system crash and so on

  • If the finally block is to be executed by the daemon thread and all other non-daemon threads exit before the finally call

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 6…

The author suggests: I can’t answer so much, master in the world!

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️