Can anyone explain this code of HackerRank?
class DoNotTerminate {
public static class ExitTrappedException extends SecurityException {
private static final long serialVersionUID = 1;
}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
This following code will stop you from terminating the code using exit(0)!
When a program tries to stop the JVM by calling
System.exit(...), then it first checks if this action is allowed by asking the security manager if theexitVMpermission is granted.The code you posted replaces the security manager with a custom security manager that will throw an
ExitTrappedExceptionwhen checking for theexitVMpermission.So, what happens is this:
System.exit(...)System.exit(...)method asks the security manager if theexitVMpermission is allowedExitTrappedExceptionSystem.exit(...)does not continue to stop the JVM, but passes the exception on the caller; the JVM keeps running