当应用程序发生异常而没有捕获到,会导致程序挂掉,可以添加一个钩子线程,在jvm退出前执行钩子线程中的代码
public class Demo { public static void main(String[] args) throws Exception, SecurityException { //给应用添加一个钩子线程,jvm退出时会执行 Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("exit jvm "); })); int i = 0; int a = 0; while(true) { i ++; Thread.sleep(1_000); System.out.println("i = "+ i); if(i == 10) { a = 3/0; } } } }