Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The compliant solution installs a custom security manager PasswordSecurityManager that overrides the checkExist method defined in SecurityManager class. An internal flag is used to keep track of whether the exit is permitted or not. The method setExitAllowed is used to set this flag to true. If the flag is false, a SecurityException is thrown. The System.exit call is not permitted to execute by catching the SecurityException in a try-catch block. After intercepting and performing mandatory clean-up operations, the setExitAllowed method is invoked. The program as a result exits gracefully.

Code Block
bgColor#ccccff
public class PasswordSecurityManager extends SecurityManager{
  private boolean flag; 
  
  public PasswordSecurityManager(){
    super();
    flag = false;  
  }
 
 public boolean isExitAllowed(){
   if(flag == true)
     return true;
   else
     return false;	 
 }
 
 public void checkExit(int status) {
   if(!isExitAllowed())
     throw new SecurityException();
   }
 
 public void setExitAllowed(boolean f) {
   if(f == true)
     flag = true;
   else
     flag = false; 	 
 }
}

public class InterceptExit {
  public static void main(String[] args) {
    PasswordSecurityManager secManager = new PasswordSecurityManager();
    System.setSecurityManager(secManager);
    try {
      System.out.println("Regular code block");
      System.exit(1);  //abrupt exit call
    }
    catch (Throwable x) {
      if (x instanceof SecurityException)
        System.out.println("Intercepted System.exit()");
      else
        x.printStackTrace();
    }

    System.out.println("Executing code block...");
    secManager.setExitAllowed(true);  //permit exit
    System.out.println("Finished block, exiting...");  //exit finally 
  }
}

...