这个问题在这里已有答案:
我已经开发了一个程序,其中返回语句的情况在try块或catch块中,finally块最后执行但是当我在try块中写入system.exit时,在这种情况下finally块没有被执行但仍然我想执行,你有没有建议我是否需要添加 Runtime.getRuntime().addShutdownHook
在这种情况下我需要添加应该在任何情况下执行的代码,即使调用了system.exit . 请指教,下面是我的 class
public class Hello {
public static void hello(){
try{
System.out.println("hi");
System.exit(1);
// return;
}catch(RuntimeException e)
{ //return;
}
finally{
System.out.println("finally is still executed at last");
}
}
public static void main(String[] args){
Hello.hello();
}
}
2 回答
1)一般来说,如果你想在退出后执行一些代码,你需要一个关闭钩子
2)在这个具体的情况下,不需要关闭钩子,只需从代码中删除退出
当你调用System.exit(1)时
它会退出程序,JVM会强制停止执行程序 .
那么,如果你想在退出后执行一些代码,为什么要使用System.exit(1)呢?
只需在你的try块中应用一些条件来退出try块,这会在每种情况下导致finnaly阻塞