File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes finally blocks (with respect to JVM Shutdown vs System.exit(0)) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "finally blocks (with respect to JVM Shutdown vs System.exit(0))" Watch "finally blocks (with respect to JVM Shutdown vs System.exit(0))" New topic
Author

finally blocks (with respect to JVM Shutdown vs System.exit(0))

James Hook
Greenhorn

Joined: Jan 20, 2003
Posts: 18
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.
Kathy Sierra
Cowgirl and Author
Ranch Hand

Joined: Oct 10, 2002
Posts: 1572
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.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: finally blocks (with respect to JVM Shutdown vs System.exit(0))
 
Similar Threads
Will "finally" block always run?
how to restart my application
Returning error code from jar application
how to end all threads before ending main
finally clause