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

前端 未结 10 2033
执念已碎
执念已碎 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:00

    Yes, the finally block will always be run, unless there is a crash of the JVM (very rare, but that can happen).

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

    the only exceptions finally block is not executed are, either JVM crashes, or system.exit().

    0 讨论(0)
  • Absolutely, that finally block will run, every time. Except in the case of a JVM crash or the exit() function being called. I have had code where the Java application made calls out to JNI native code which segfaulted. The resulting crash killed the JVM, and prevented the finally from running.

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

    It is not guaranteed:

    public class Main {
        public static void main(String args[]) {
            try {
                System.out.println("try");
                System.exit(0);
            } catch (Exception e) {
                System.out.println("exception");
            } finally {
                System.out.println("finally");
            }
        }
    }
    

    Run that.

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

    Chris Cameron is correct. But normally a finally-block gets executed. Null pointer dereferece does exist in Java:

    try {
        List<Object> x = null;
        x.get(1); //throws the unchecked NullPointerException
    } finally {
        //will be executed
    }
    

    The finally-Block gets executed.

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

    It seems pretty obvious that nothing more will run after JVM quit, or will run code in that killed thread. Obvious. So, when the JVM is running, every code that will run, will run, and after a JVM quit or inside a dead thread , nothing will run, even any kind of code. So, there is no way to prevent, but if there is a need to the finally clause, put it.

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