Week 75 — What is the exit code of a program and how can exit codes be set from Java code?
Question of the Week #75
What is the exit code of a program and how can exit codes be set from Java code?
3 Replies
When a program stops, it can send an "exit code" (or "status code") back to the system. This can be used to give information on whether the program completed successfully or not.
If a program is called by a script, the script can access this exit code accordingly.
Java allows setting exit codes by passing an
int
to System.exit
. If System.exit
is not used, the program terminates using the exit code 0
.
For example, the following program prints the first argument if present and stops with exit code 1
if that argument isn't present:
📖 Sample answer from dan1st
The exit code is a single byte signed integer stored in an environment variable after process termination.
This is the only way I know of to terminate a Java program and set an exit code.
Standard convention uses '0' for a normal voluntary exit with anything else indicating a error exit, fatal error, or killed by another process.
Sometimes a project will have documentation for what exit codes mean.
Submission from floington500
An exit code is an integer that a process is allowed to return to the operating system or command execution environment. It is used to indicate the overall status of the process. The exact valid ranges and meanings are platform-specific and often just a convention, rather than a hard specification or requirement. Generally, an exit code of
0
indicates success, whereas higher values indicate an error.
In Java, an exit code can be returned from the process by calling System.exit(someCode)
:
If this program is run in something like a Bash shell, then the exit code of 3
will be available to the shell:
Submission from dangerously_casual