• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1589
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic