0

I have developed a program in which the case of return statement either inside try block or catch block the finally block executes at last but when I write system.exit inside try block in this case the finally block not executed but still I want to execute , could you please advise do I need to add Runtime.getRuntime().addShutdownHook in that case I need to add the code that should be executed in any case , even if system.exit is called. please advise , below is my 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();
    }
}
user2129402
  • 85
  • 1
  • 6

2 Answers2

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");
    }
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Thanks a lot, as suggested by you let say in the above program of mine I want to print simple sop statement after the program execution through shutdown hook , Could you please show by making code changes in my above program – user2129402 Mar 07 '13 at 06:18
  • ok, added example of shudown hook – Evgeniy Dorofeev Mar 07 '13 at 06:29
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