Mehraj Malik Mehraj Malik - 5 months ago 20
Java Question

System.exit(0) does not prevent finally being called when have a SecurityManager.checkExit throw an exception

I have a problem with

System.exit(0);
.
When I tried the below code the output was nothing because of
System.exit(0);
:

String number = "12345M";
try {
System.exit(0);
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("inside finally");
}


But when I tried this below code:

System.setSecurityManager(new SecurityManager() {
@Override
public void checkExit(int status) {
throw new ThreadDeath();
}
});

try {
System.exit(0);
} finally {
System.out.println("I am finally block");
}


The output was:


I am finally block


Can someone please explain this different behavior?

Answer

Because exit was prevented by the ThreadDeath exception (which is not one you should be throwing yourself btw):

SecurityException - if a security manager exists and its checkExit method doesn't allow exit with the specified status.

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit(int)

Note that you should throw a SecurityException to prevent exit e.g.:

System.setSecurityManager(new SecurityManager() {
    @Override
    public void checkExit(int status) {
        throw new SecurityException("Not allowed.");
    }
});

try {
    System.exit(0);
} catch(SecurityException e) {
    System.out.println("Exit failed.");
} finally {
    System.out.println("I am  finally block");
}
System.out.println("Program still running");

Output:

Exit failed.
I am  finally block
Program still running