How to exit a program with an exit code
Short answer
System.exit(code) ends the program at once. Code 0 means success, anything else means an error:
void main() {
String[] files = {};
if (files.length == 0) {
IO.println("Nothing to process");
System.exit(2);
}
IO.println("Processing...");
}Output:
Nothing to processCheck the exit code in the shell: in bash echo $?, in PowerShell $LASTEXITCODE. Here it is 2.
A normal exit
If the exit code is 0, System.exit() is not needed: just leave main with return:
void main() {
int[] items = {1, 2, 3};
if (items.length > 0) {
IO.println("Found " + items.length + " items");
return;
}
IO.println("Not reached");
}Output:
Found 3 itemsThe code on an exception
An uncaught exception in main also ends the program, and the exit code is 1. An error exit is clearer with a readable message in System.err:
void main() {
try {
Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.err.println("Bad number: " + e.getMessage());
System.exit(1);
}
}Output:
Bad number: For input string: "abc"Actions before exiting
addShutdownHook() registers code that runs on any normal termination, including System.exit():
void main() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> IO.println("Saving state...")));
IO.println("Working");
System.exit(0);
}Output:
Working
Saving state...Common mistake
Calling System.exit() deep inside methods. It stops the whole JVM: finally blocks do not run, tests are cut short, and in a web server the whole application goes down. Throw an exception instead and decide whether to exit only in main.
Functions used in this recipe
- System.exit() — Terminates the program immediately with the given exit code.
- 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.