开发者

is there any code, that will never execute finally clause? [duplicate]

开发者 https://www.devze.com 2023-02-23 06:09 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate开发者_StackOverflow:
This question already has answers here: Closed 11 years ago.

Possible Duplicate开发者_StackOverflow:

Is there such case when in try\finally block the finally won't be executed?

is there any code, that will never execute finally clause?


Java Tutorials

Not only for System.exit , but also for thread interrupted

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


System.exit(0) is one example. If you compile and run below "Bye" will never get printed.

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Hi");
            System.exit(0);
        }
        finally {
            System.out.println("Bye!");
        }
    }
}


System.exit(0) if does not throw security exception.


Here's another example:

try {
    while (true) {
       System.err.println("Its great to be alive");
    }
} finally {
    System.err.println("I wish!");
}


System.exit(0);


In short words, finally block is not executed if JVM is stopped while thread is inside a corresponding try block, or if thread is killed using some low-level mechanisms (not Thread.stop()).

In addition to obvious examples with System.exit(), even a normal JVM shutdown can be unexpected for daemon threads:

public static void main(String[] args) throws Exception {
    final CountDownLatch c = new CountDownLatch(1);

    Thread t = new Thread() {
        public void run() {
            try {
                System.out.println("Entering try block");
                c.countDown();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {}
            } finally {
                System.out.println("Never printed");
            }
        }
    };
    t.setDaemon(true);
    t.start();
    c.await();
    System.out.println("Exiting main thread");
}


Also on my workout i found a new solution for this, is this can be accepcable

try {
if (choice) {
  while (true) ;
} else {
  System.exit(1);
}
} finally {
code.to.cleanup();

}

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号