System.exit() method in Java
In this post, we will explore the System.exit() method in Java, and explain its advantages and disadvantages.
An exit code is an integer value that represents the status of a program termination. An exit code can be used to indicate whether a program has completed successfully or encountered an error. There are different types of exit codes that have different meanings and implications.
1. Overview of System.exit() method
The System.exit() method is a static void method of the System class that terminates the current Java virtual machine (JVM) and exits the program. The System.exit() method takes an exit code as an argument and passes it to the operating system or the calling script. The exit code can be any integer value, but the general convention is that a zero value indicates a normal termination, while a non-zero value indicates an abnormal termination.
- Zero status code should be used when the program is terminated successfully.
- Positive status codes are often used for user-defined codes to indicate a particular exception.
- Negative status codes are system generated error codes. They are generated due to some unanticipated exception, system error, or forced termination of the program.
The System.exit() method offers the following benefits:
- The
System.exit()method allows fast termination of the program by using a single line of code. It does not require creating an object or throwing an exception to terminate the program. - The
System.exit()method can be used to communicate with the operating system or the calling script by passing an exit code. The exit code can be used to indicate the status or reason of the program termination, such as success, failure, error, exception, etc. - The
System.exit()method can be used to invoke any shutdown hooks that have been registered with theRuntimeclass. These hooks are threads that run before the JVM exits and can be used to perform some cleanup tasks, such as closing resources, saving data, logging messages, etc. - The
System.exit()method can be used to terminate the program from any place other than the main method, such as from another thread or from a catch block. This can be useful when there is an unrecoverable error or condition and we need to exit the program immediately.
Let’s see an example of how to use the System.exit() method in Java:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Random; class Main { public static void main(String[] args) { // randomly generate either -1, 0, or 1 int num = new Random().nextInt(-1, 2); // Check if the number is positive or negative if (num > 0) { // Exit with code 0 (normal termination) System.exit(0); } else if (num < 0) { // Exit with code 1 (abnormal termination) System.exit(1); } else { // Exit with code -1 (abnormal termination with exception) throw new RuntimeException("Zero is not allowed."); } } } |
Please note that:
- There are no pre-defined constants in Java to indicate SUCCESS and FAILURE messages.
- We should always use the proper status codes if our application interact with some tools or the program is called within a script.
System.exit()method internally calls exit() method of theRuntimeclass. Therefore, the callSystem.exit(n)is effectively equivalent to the call:Runtime.getRuntime().exit(n).
2. Drawbacks of System.exit() method
The System.exit() method is not without its limitations compared to other types of exit codes. Here are some of the main drawbacks of using the System.exit() method in Java:
- The
System.exit()method is not recommended for normal termination of the program. It is better to use return statements or throw exceptions instead of usingSystem.exit(). This way, we can ensure that the program exits gracefully and follows the normal control flow. - The
System.exit()method does not guarantee that all the shutdown hooks will run before the JVM exits. Some hooks may not run at all or may run only partially. This can cause data loss, resource leak, or inconsistent state. - The
System.exit()method does not allow any finally blocks to execute after it is called. This means that any cleanup code that is written in finally blocks will be skipped and ignored. This can also cause data loss, resource leak, or inconsistent state. - The
System.exit()method can cause security issues if it is called by untrusted code. A malicious code can useSystem.exit()to terminate the JVM and prevent other applications from running. This can also cause denial of service attacks or data corruption.
3. How to use System.exit() Method in Java correctly?
As we have seen, System.exit() method is a powerful and useful method to terminate the program and communicate with the operating system or the calling script. Here are some general recommendations on how to use System.exit() method in Java correctly:
- Use
System.exit()method only when there is an unrecoverable error or condition and we need to exit the program immediately. Do not useSystem.exit()method for normal termination of the program. Use return statements or throw exceptions instead. - Use meaningful and consistent exit codes to indicate the status or reason of the program termination. Follow the convention that zero means normal termination and non-zero means abnormal termination. Avoid using negative values or large values as exit codes.
- Register shutdown hooks with the
Runtimeclass to perform some cleanup tasks before the JVM exits. However, do not rely on them to run completely or in a specific order. Make sure that the hooks are simple, fast, and thread-safe. - Avoid calling
System.exit()method from try-catch-finally blocks, as finally block will not execute afterSystem.exit()method is called. Instead, move the cleanup code to shutdown hooks or try-with-resources blocks. - Use a security manager to prevent untrusted code from calling
System.exit()method and terminating the JVM. Override thecheckExit()method of the security manager to throw aSecurityExceptionif an untrusted code tries to callSystem.exit()method.
That’s all about exit codes in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)