0

我已经开发了一个程序,其中在 try 块或 catch 块中返回语句的情况最后执行 finally 块但是当我在这种情况下在 try 块中编写 system.exit 时,finally 块没有执行但我仍然想执行,您能否建议我是否需要在这种情况下添加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();
    }
}
4

2 回答 2

1

1) in general you do need a shutdown hook if you want to execute some code after exit

public static void main(String[] args) throws Exception {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("bye");
        }
    });
    hello();
}

2) in this concrete case there's no need for shutdown hook, just remove exit from the code

public static void hello() {
    try{
        System.out.println("hi");
    } catch (RuntimeException e) {
        //
    } finally{
        System.out.println("finally is still executed at last");
    }
}
于 2013-03-07T06:01:24.053 回答
0

when you are calling System.exit(1)

it exits your program and JVM stops the execution of your program by force .

so why would you use System.exit(1) if you want some code to execute after the exit

simply apply some condition within yout try block to exit try block , which leads to finnaly block in every case

于 2013-03-07T06:03:06.907 回答