javasecuritymanager

Preventing System.exit() from API


I am using a third party library that does a System.exit() if it encounters exceptions. I am using the APIs from a jar. Is there anyway that I can prevent the System.exit() call because it causes my application to shutdown? I cannot decompile and recompile the jar after removing the System.exit() because of a lot of other licensing issues. I once came across an answer [to some other question that I do not remember] in stackoverflow that we can use the SecurityManager in Java to do something like this.


Solution

  • You can install a security manager which disables System.exit():

      private static class ExitTrappedException extends SecurityException { }
    
      private static void forbidSystemExitCall() {
        final SecurityManager securityManager = new SecurityManager() {
          public void checkPermission( Permission permission ) {
            if( "exitVM".equals( permission.getName() ) ) {
              throw new ExitTrappedException() ;
            }
          }
        } ;
        System.setSecurityManager( securityManager ) ;
      }
    
      private static void enableSystemExitCall() {
        System.setSecurityManager( null ) ;
      }
    

    Edit: Max points out in comments below that

    as of Java 6, the permission name is actually "exitVM."+status, e.g. "exitVM.0".

    However, the permission exitVM.* refers to all exit statuses, and exitVM is retained as a shorthand for exitVM.*, so the above code still works (see the documentation for RuntimePermission).