为什么 finally 块不执行?

why finally block doesn't execute?

为什么这段代码finally块没有执行?它只打印 1. Is finally block not execute after System.exit(0); ?

    void method2() {
    try {
        System.out.println("1");
        System.exit(0);
    } finally {
        System.out.println("3");
    }
}

System.exit(0) 实际上完全停止了程序的执行。删除 System.exit 因为您实际上并没有尝试在那里退出代码。

删除 SYSTEM.EXIT 因为这会退出整个程序,而不管它后面是什么。虽然它在尝试它仍然进入代码块:)

System.exit(0)finally 块执行之前终止运行时。将其移至 System.out 之后的 finally 区块。

System.exit(); 关闭虚拟机。在此之后唯一可以执行的是使用 Runtime.addShutdownHook(Thread).

创建的关闭挂钩