public class ShutDownHook {
public static void main(String[] args) {
// try and run before shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Shutdown Hook is running....");
}
});
try {
System.out.println("Inside try");
// throw an exception
int x = 10 / 0;
} catch (Exception e) {
System.out.println("Inside catch");
// Shut down and test hook
System.exit(0);
} finally {
// should not run
System.out.println("Inside finally");
}
}
}
Output:
$ java ShutDownHook Inside try Inside catch Shutdown Hook is running....