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");
}
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");
}
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 {
}