A Guide to System.exit()

1. Overview

In this tutorial, we’ll have a look at what System.exit means in Java.

We’ll see its purposes, where to use and how to use it. We’ll also see what’s the difference in invoking it with different status codes.

2. What Is System.exit?

System.exit is a void method. It takes an exit code, which it passes on to the calling script or program.

Exiting with a code of zero means a normal exit:

System.exit(0);

We can pass any integer as an argument to the method. A non-zero status code is considered as an abnormal exit.

Calling the System.exit method terminates the currently running JVM and exits the program. This method does not return normally.

This means that the subsequent code after the System.exit is effectively unreachable and yet, the compiler does not know about it.

System.exit(0);
System.out.println("This line is unreachable");

It’s not a good idea to shut down a program with System.exit(0). It gives us the same result of exiting from the main method and also stops the subsequent lines from executing, also the thread invoking System.exit blocks until the JVM terminates. If a shutdown hook submits a task to this thread, it leads to a deadlock. 

3. Why Do We Need It?

The typical use-case for System.exit is when there is an abnormal condition and we need to exit the program immediately.

Also, if we have to terminate the program from a place other than the main method, System.exit is one way of achieving it.

4. When Do We Need It?

It’s common for a script to rely on the exit codes of commands it invokes. If such a command is a Java application, then System.exit is handy for sending this exit code.

For example, instead of throwing an exception, we can return an abnormal exit code that can then be interpreted by the calling script.

Or, we can use System.exit to invoke any shutdown hooks we’ve registered. These hooks can be set to clean up the resources held and exit safely from other non-daemon threads.

5. A Simple Example

In this example, we try to read a file and if it exists, we print a line from it. If the file does not exist, we exit the program with System.exit from the catch block.

try {
    BufferedReader br = new BufferedReader(new FileReader("file.txt"));
    System.out.println(br.readLine());
    br.close();
} catch (IOException e) {
    System.exit(2);
} finally {
    System.out.println("Exiting the program");
}

Here, we must note that the finally block does not get executed if the file is not found. Because the System.exit on the catch blocks exits the JVM and does not allow the finally block to execute.

6. Choosing a Status Code

We can pass any integer as a status code but, the general practice is that a System.exit with status code 0 is normal and others are abnormal exits.

Note that this is only a “good practice” and is not a strict rule that the compiler would care about.

Also, it’s worth noting when we invoke a Java program from the command-line that the status code is taken into account.

In the below example, when we try to execute SystemExitExample.class, if it exits the JVM by calling the System.exit with a non-zero status code, then the following echo does not get printed.

java SystemExitExample && echo "I will not be printed"

To make our program able to communicate with other standard tools, we might consider following the standard codes that the related systems use to communicate.

For example, UNIX status codes define 128 as the standard for “invalid argument to exit”. So, it might be a good idea to use this code when we need our status code to be communicated to the operating system. Otherwise, we are free to choose our code.

7. Conclusion

In this tutorial, we discussed how System.exit works when to use it, and how to use it.

It’s a good practice to use exception handling or plain return statements to exit a program when working with application servers and other regular applications. Usage of System.exit method suit better for script-based applications or wherever the status codes are interpreted.

You can check out the examples provided in this article over on GitHub.

Related posts:

@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Java Program to Perform Encoding of a Message Using Matrix Multiplication
Lớp Collections trong Java (Collections Utility Class)
Java Program to implement Bit Matrix
Java Program to Implement Disjoint Sets
Guide to the ConcurrentSkipListMap
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Java Program to Find a Good Feedback Edge Set in a Graph
Giới thiệu Java 8
Documenting a Spring REST API Using OpenAPI 3.0
Convert a Map to an Array, List or Set in Java
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Java Program to Implement ConcurrentLinkedQueue API
Java Program to Implement RenderingHints API
Exploring the Spring Boot TestRestTemplate
Simple Single Sign-On with Spring Security OAuth2
Java Program to Implement Merge Sort on n Numbers Without tail-recursion
Java Program to Solve any Linear Equations
Java Program to Implement Strassen Algorithm
Java Program to Remove the Edges in a Given Cyclic Graph such that its Linear Extension can be Found
Java Program to Implement ArrayList API
Command-Line Arguments in Java
The Thread.join() Method in Java
Quick Guide on Loading Initial Data with Spring Boot
Tính đóng gói (Encapsulation) trong java
Guide to the Volatile Keyword in Java
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Spring – Injecting Collections
Java Program to Implement Sorted Array
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Jackson – Unmarshall to Collection/Array
Java Program to Implement Euclid GCD Algorithm