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:

Removing all Nulls from a List in Java
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java equals() and hashCode() Contracts
Java Program to Implement Miller Rabin Primality Test Algorithm
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Build a REST API with Spring and Java Config
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
How to Iterate Over a Stream With Indices
A Guide to HashSet in Java
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
An Intro to Spring Cloud Security
Guide to @ConfigurationProperties in Spring Boot
Java Program to Implement Stack API
Java Program to Create a Random Graph Using Random Edge Generation
Java Program to Implement Best-First Search
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
A Guide to WatchService in Java NIO2
Finding Max/Min of a List or Collection
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Sử dụng CyclicBarrier trong Java
A Guide to Spring Boot Admin
Java – Try with Resources
Tips for dealing with HTTP-related problems
Spring Security Basic Authentication
Guide to the Volatile Keyword in Java
Giới thiệu SOAP UI và thực hiện test Web Service
Java Program to Generate All Possible Subsets with Exactly k Elements in Each Subset
ExecutorService – Waiting for Threads to Finish
Jackson – Decide What Fields Get Serialized/Deserialized
Quick Guide on Loading Initial Data with Spring Boot
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected