How does Java's System.exit() work with try/catch/finally blocks? [duplicate]

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

System.exit(int) can throw a SecurityException. If that happens, the finally block will be executed. And since the same principal is calling the same method from the same code base, another SecurityException is likely to be thrown from the second call.


Here's an example of the second case:

import java.security.Permission;

public class Main
{

  public static void main(String... argv)
    throws Exception
  {
    System.setSecurityManager(new SecurityManager() {

      @Override
      public void checkPermission(Permission perm)
      {
        /* Allow everything else. */
      }

      @Override
      public void checkExit(int status)
      {
        /* Don't allow exit with any status code. */
        throw new SecurityException();
      }

    });
    System.err.println("I'm dying!");
    try {
      System.exit(0);
    } finally {
      System.err.println("I'm not dead yet!");
      System.exit(1);
    }
  }

}

Simple tests including catch too reveal that if system.exit(0) does not throw a security exception, it will be the last executed statement (catch and finally are not executed at all).

If system.exit(0) does throw a security exception, catch and finally statements are executed. If both catch and finally contain system.exit() statements, only statements preceding these system.exit() statements are executed.

In both cases decribed above, if the try code belongs to a method called by another method, the called method does not return.

More details here (personal blog).


Other answers have covered how the catch and finally blocks don't run if System.exit exits the JVM without throwing a SecurityException, but they don't show what happens in a "try-with-resources" block to the resources: Are they closed?

According to the JLS, Section 14.20.3.2:

The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

That is, resources will be closed before a catch or finally block runs. What if they are closed somehow even if catch and finally don't run?

Here's some code to demonstrate that the resources in a "try-with-resources" statement aren't closed either.

I use a simple subclass of BufferedReader that prints a statement before calling super.close.

class TestBufferedReader extends BufferedReader {
    public TestBufferedReader(Reader r) {
        super(r);
    }

    @Override
    public void close() throws IOException {
        System.out.println("close!");
        super.close();
    }
}

Then I set up the test case of calling System.exit in the try-with-resources statement.

public static void main(String[] args)
{
    try (BufferedReader reader = new TestBufferedReader(new InputStreamReader(System.in)))
    {
        System.out.println("In try");
        System.exit(0);
    }
    catch (Exception e)
    {
        System.out.println("Exception of type " + e.getClass().getName() + " caught: " + e.getMessage());
    }
    finally
    {
        System.out.println("finally!");
    }
}

Output:

In try

Therefore, not only do catch and finally blocks not run, a "try-with-resources" statement won't get a chance to close its resources if System.exit succeeds.


finally block will be executed no matter what....even if try block throws any throwable(exception or error).....

only case finally block does not execute...is when we call System.exit() method..

try{
    System.out.println("I am in try block");
    System.exit(1);
} catch(Exception ex){
    ex.printStackTrace();
} finally {
    System.out.println("I am in finally block!!!");
}

It will not execute finally block. The program will be terminated after System.exit() statement.


If you consider this behaviour problematic, and you need fine control over your System.exit calls, then the only thing you can do is wrap the System.exit functionality in your own logic. If we do that, we can get finally blocks executed and get resources closed as part of our exit flow.

What I'm considering doing is wrapping the System.exit call & functionality in my own static method. In my implementation of exit I would throw a custom subclass of Throwable or Error, and implement a custom Uncaught exception handler with Thread.setDefaultUncaughtExceptionHandler to handle that exception. Thus my code becomes:

//in initialization logic:
Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> {
  if(exception instanceof SystemExitEvent){
    System.exit(((SystemExitEvent)exception).exitCode);
  }
})

// in "main flow" or "close button" or whatever
public void mainFlow(){
  try {
    businessLogic();
    Utilities.exit(0);
  }
  finally {
    cleanUpFileSystemOrDatabaseConnectionOrWhatever();  
  }
}

//...
class Utilities {

  // I'm not a fan of documentaiton, 
  // but this method could use it.
  public void exit(int exitCode){
    throw new SystemExitEvent(exitCode);
  }
}

class SystemExitEvent extends Throwable { 
  private final int exitCode;

  public SystemExitEvent(int exitCode){
    super("system is shutting down")
    this.exitCode = exitCode;
  }
} 

This strategy has the added "benefit" of making this logic testable: to test that the method containing our "main flow" actually requests the system to exit, all we have to do is catch a throwable and assert that is the write type. For example, a test for our business logic wrapper might look like:

//kotlin, a really nice language particularly for testing on the JVM!

@Test fun `when calling business logic should business the business`(){
  //setup
  val underTest = makeComponentUnderTest(configureToReturnExitCode = 42);

  //act
  val thrown: SystemExitEvent = try {
    underTest.mainFlow();
    fail("System Exit event not thrown!")
  }
  catch(event: SystemExitEvent){
    event;
  }

  //assert
  assertThat(thrown.exitCode).isEqualTo(42)

The major downside to this strategy is that it is a way of getting functionality out of exception flow, which often has unintended consequences. The most obvious one, in this case, is that anywhere you've written try { ... } catch(Throwable ex){ /*doesnt rethrow*/ } will have to be updated. In the case of libraries that have custom execution contexts, they will need to be retrofitted to also understand this exception.

On balance, this seems like a good strategy to me. Does anybody else here think so?