In Java, is the “finally” block guaranteed to be called (in the main method)?

前端 未结 10 2034
执念已碎
执念已碎 2020-12-06 09:17

I\'m a Java rookie and I was wondering, if I have the following typical Java code

public class MyApp {
  public static void main(String[] args) {
    try {
          


        
相关标签:
10条回答
  • 2020-12-06 10:12

    Basically yes, except for the note listed here (emphasis mine):

    If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    0 讨论(0)
  • 2020-12-06 10:13

    Yes, the JVM always executes it. Gaurranteed.

    Of course ... if the JVM itself dies (eg: System.exit()), then it's not in a position to gaurrantee anything. But the JVM dying is not a within-java issue.

    0 讨论(0)
  • 2020-12-06 10:19

    In a word, yes.

    Code in the finally block in Java always executes unless:

    • The JVM exits during the try or catch block
    • The thread running the code is interrupted or killed during the try or catch block

    (from: http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html)

    So, unless you explicitly call System.exit(int), or kill the process or thread externally, you can rely on it.

    0 讨论(0)
  • 2020-12-06 10:20

    Erm, yep :) Whether your code enters a catch or not, the finally will run. It's a good place to put code that cleans up after the try.

    Obviously it won't run if you break the jvm :)

    0 讨论(0)
提交回复
热议问题