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?
No. System. exit(0) doesn't return, and the finally block is not executed.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With