#Week 75 — What is the exit code of a program and how can exit codes be set from Java code?

3 messages · Page 1 of 1 (latest)

astral waveBOT
#
Question of the Week #75

What is the exit code of a program and how can exit codes be set from Java code?

gaunt cosmosBOT
#

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:

public class PrintFirstArgumentOrExit1{
  public static void main(String[] args){
    if(args.length==0){
      System.out.println("no argument passed");
      System.exit(1);//stop with exit code 1
    }
    System.out.println("The first argument is: "+args[0]);
    //Sysem.exit was not called hence the program uses exit code 0
  }
}
📖 Sample answer from dan1st
#

The exit code is a single byte signed integer stored in an environment variable after process termination.

System.exit(0); //-127 to 127

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