-1

Can anyone tell me how to execute finally still if an exception raised and the catch is calling System.exit

try {   
} catch (Exception e) {
    System.exit(0);
} finally {
    System.out.println("closing the conn");
}
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
Prashant
  • 17
  • 1
  • 6
  • You could also use [`Runtime.getRuntime().addShutdownHook(Thread)`](http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)). as mentioned [here](https://stackoverflow.com/questions/5747803/running-code-on-program-exit-in-java) – JorgeGarza Nov 20 '17 at 18:30

1 Answers1

0

System.exit() normally never returns so you will not execute the code in the finally block as you have it written.

One way you can do it is to note the fact that you had an error in the catch block then do the exit in the finally block.

boolean error = false;

try {
   // bla bla blaa

} catch (Exception e) {
    error = true;
}
finally {
    if (error)  {
        System.exit(0);
    }
}

Another way to do it is to add a shutdown hook that will get called as the JVM is exiting.

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Do your shutdown stuff here");
    }
}));

try {
    // bla bla blah     
} catch (Exception e) {
    System.exit(0);
} finally {
}
JJF
  • 2,681
  • 2
  • 18
  • 31
  • This is ok to write, but I think we have changed the code , isnt there a way to close the connection in finally before System.exit in catch – Prashant Apr 03 '16 at 17:12
  • try { connection.open() } catch (Exception e) { System.exit(0); } finally { System.out.println("closing the conn"); connection.close() } – Prashant Apr 03 '16 at 17:13
  • @user3431510. Short answer is no. I edited my answer and gave you another possible solution. – JJF Apr 03 '16 at 18:01
  • Similar question has been asked, take a look at to this [answer](https://stackoverflow.com/a/52623234/3627279) – Joe Oct 03 '18 at 08:57