我已经开发了一个程序,在这个程序中,返回语句的情况在try块或catch块中最后执行,但是当我在try块中编写system.exit时,在这种情况下,最终块没有执行,但我仍然想执行,您能建议我是否需要添加Runtime.getRuntime().addShutdownHook
在这种情况下,我需要添加在任何情况下都应该执行的代码,即使调用了system.exit。敬请指教,下面是我的班级
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();
}
}
发布于 2013-03-07 14:01:24
1)通常,如果您想在退出后执行一些代码,则确实需要一个关闭钩子
public static void main(String[] args) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("bye");
}
});
hello();
}
2)在这个具体的例子中,不需要关闭钩子,只需从代码中删除exit
public static void hello() {
try{
System.out.println("hi");
} catch (RuntimeException e) {
//
} finally{
System.out.println("finally is still executed at last");
}
}
发布于 2013-03-07 14:03:07
当您调用System.exit(1)时
它会退出您的程序,并且JVM会强制停止您的程序的执行。
那么,如果您希望一些代码在退出后执行,为什么还要使用System.exit(1
只需在yout try块中应用一些条件即可退出try块,这在任何情况下都会导致finnaly块
https://stackoverflow.com/questions/15264076
复制相似问题