System.exit()
Terminates the program immediately with the given exit code.
Available since: Java 1.0
Syntax
public static void exit(int status)Parameters
| Parameter | Type | Description |
|---|---|---|
| status | int | The exit code: 0 means success, any other number means an error. |
Examples
Stopping with code 1 when something went wrong. The line Started is never printed:
void main() {
IO.println("Checking config...");
boolean configFound = false;
if (!configFound) {
IO.println("Config not found");
System.exit(1);
}
IO.println("Started");
}Output:
Checking config...
Config not foundAfter System.exit() even the finally block does not run:
void main() {
try {
IO.println("in try");
System.exit(0);
} finally {
IO.println("in finally");
}
}Output:
in tryNotes
Whoever started the program sees the exit code: in bash it is echo $?, in PowerShell $LASTEXITCODE. Scripts and CI systems use it to tell whether the program succeeded. If main simply finishes, the exit code is 0; on an uncaught exception it is 1. Hooks registered with Runtime.getRuntime().addShutdownHook(...) run before the exit. Libraries and server applications do not call System.exit(): it stops the whole JVM, not just your code.
See also
- System.getenv() — Returns the value of an environment variable, or null if it is not set.
- Runtime.getRuntime() — Returns the Runtime object of the current JVM: memory, processor count, shutdown hooks.
- return — Ends a method and gives a value back to the caller.
Related recipes
In the tutorial
- Arguments, environment and exit codes — How a Java program gets settings from outside — command-line arguments, environment variables with System.getenv, system properties with System.getProperty and -D, and exit codes with System.exit.