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:

ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Convert Time to Milliseconds in Java
Tránh lỗi ConcurrentModificationException trong Java như thế nào?
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman
Java Program to Implement Hash Tables
Spring @RequestParam Annotation
Java Program to Implement Naor-Reingold Pseudo Random Function
LinkedHashSet trong java
Giới thiệu java.io.tmpdir
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Chuyển đổi từ HashMap sang ArrayList
How to Read HTTP Headers in Spring REST Controllers
Spring Boot with Multiple SQL Import Files
Java Program to Implement Branch and Bound Method to Perform a Combinatorial Search
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java Program to Implement Self organizing List
Database Migrations with Flyway
Java Program to Represent Graph Using 2D Arrays
Java Program to Implement Flood Fill Algorithm
Add Multiple Items to an Java ArrayList
Serverless Functions with Spring Cloud Function
Merging Streams in Java
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Java Program to Implement Heap Sort Using Library Functions
Unsatisfied Dependency in Spring
Query Entities by Dates and Times with Spring Data JPA
Simplify the DAO with Spring and Java Generics
Assertions in JUnit 4 and JUnit 5
Guide to Guava Table
CyclicBarrier in Java