Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 924
Mehraj Malik Avatar asked Jun 17 '16 07:06

Mehraj Malik


People also ask

Will the finally block be executed if the code system Exit 0 is written at the end of try block?

No. System. exit(0) doesn't return, and the finally block is not executed.

Is finally called after system exit?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java. If we call the System. exit() method explicitly in the finally block then only it will not be executed.

What is the system Exit 0 method Why is it used?

exit(0) : Generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination. Note : This method does not return any value.

How do you exit a mock system?

ANSWER: You actually can mock or stub out the System. exit method, in a JUnit test. The production code uses the ExitManagerImpl and the test code uses ExitManagerMock and can check if exit() was called and with which exit code.


1 Answers

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
like image 60
weston Avatar answered Oct 04 '22 13:10

weston