finally blocks (with respect to JVM Shutdown vs System.exit(0))
Joined: Jan 20, 2003
In one of the mock exams I have taken (the Sun one!) I have been marked wrong for thinking that the only time the finally block will not run is if JVM is shutdown. Should I consider JVM shutdown and System.exit to be two different scenarios for the purposes of the exam? I am now thinking that JVM shutdown is when the JVM process is killed by the operating system.
Cowgirl and Author
Joined: Oct 10, 2002
A System.exit() will cause the VM to shutdown immediately, without running the finally. In fact, System.exit() is the ONLY thing that will stop finally from beginning to execute, although finally will not complete if finally itself has a System.exit(). So even if a runtime exception occurs in a try or catch, finally will still begin. But if try or catch has a System.exit(), that tells the VM "Stop now! Don't bother with ANYTHING else." So System.exit() is one thing that will cause the VM to shutdown, but death of the last non-daemon thread will also cause the VM to shutdown. But that thread death is often caused by uncaught exceptions, and so if there IS an uncaught exception, finally will STILL begin executing BEFORE the thread is truly considered 'dead' and the VM shuts down. I hope I made sense! Cheers, Kathy
Co-Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0596007124/ref=jranch-20" target="_blank" rel="nofollow">"Head First Design Patterns"</a><br /> <br />Just a Jini girl living in a J2EE world.
Joined: Jan 30, 2000
In fact, System.exit() is the ONLY thing that will stop finally from beginning to execute Well, unless someone kills the JVM process using Task Manager or kill -9, or ctrl-C, or the machine crashes, or power is lost, etc. Which may be sorta obvious, but is worth noting for certain types of applications.