5

If an uncaught exception is thrown during the execution of a shutdown hook in java, does the jvm exit immediately without running the rest of the registered shutdown hooks (if any)? From the javadocs:

Uncaught exceptions are handled in shutdown hooks just as in any other thread, by invoking the uncaughtException method of the thread's ThreadGroup object. The default implementation of this method prints the exception's stack trace to System.err and terminates the thread; it does not cause the virtual machine to exit or halt.

it seems like other shutdown hooks should run...

As a follow up question, its probably not a good idea to have a piece of code that could potentially throw an exception in the shutdown hook? If you can't avoid it, is it a good practice to try-catch the exception inside the shutdown hook?

fo_x86
  • 2,583
  • 1
  • 30
  • 41

2 Answers2

6

Since the addShutdownHook method takes a Thread, each individual shutdown hook is its own Thread. The default behavior for uncaught exceptions is to print an error message and terminate the Thread. Since the hooks have the same behavior, a single shutdown hook ending in error should not prevent others from running.

Note that I haven't actually tested this...

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • 1
    Thanks! I've tested this behavior, you are right, an exception in a particular shutdown hook does not prevent the other hooks from running. – fo_x86 Dec 10 '12 at 15:07
0

Code that runs inside a shutdown hook is subject to the same best practices as code that runs in your main thread: Catch exceptions if you need to, log if you need to, or let exceptions just print to stdout.

Bohemian
  • 412,405
  • 93
  • 575
  • 722