Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when an exception is thrown inside a shutdown hook in java

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?

like image 978
fo_x86 Avatar asked Dec 07 '12 20:12

fo_x86


People also ask

What is the use of shutdown hook in Java?

Shutdown Hooks are a special construct that allows developers to plug in a piece of code to be executed when the JVM is shutting down. This comes in handy in cases where we need to do special clean up operations in case the VM is shutting down.

Does throwing an exception stop execution Java?

We can throw either checked or unchecked exceptions. The throws keyword allows the compiler to help you write code that handles this type of error, but it does not prevent the abnormal termination of the program.

What happens when JVM shuts down?

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

What happens after throwing an exception Java?

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred.


1 Answers

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...

like image 195
Steven Schlansker Avatar answered Sep 22 '22 14:09

Steven Schlansker