Low Orbit Flux Logo 2 F

Java How To Exit Program

Today we’re going to talk about how to exit a Java program.

To exit a Java program use the following line:


System.exit(0);

The System.exit() method takes one parameter which is a status code. A status code of zero indicates that the program has terminated normally. Any nonzero status code indicates that the program terminated with an error. The actual value usually corresponds to a specific error.


System.exit(0);   // normal
System.exit(1);   // error code 1  
System.exit(2);   // error code 2  

NOTE - Calling System.exit() is not required to terminate a program. You can just let your program run until it completes.

Example:


class Test1 {

    public void checkSize1( int d ) {
        if( d > 10 )
            System.exit(1);   // error code 1  "too big" 
    }

    public void checkSize2( int d ) {
        if( d < 0 )
            System.exit(2);   // error code 2  "too small"
    }

    public static void main( String[] args ) {

        int d = Integer.parseInt(args[0]);
        Test1 t = new Test1();

        t.checkSize1(d); 
        t.checkSize2(d);
        System.exit(0);       // normal - everything is OK  
    }
}

The output should look like this if you are on a Unix based system like Linux, BSD, OSX, etc.


user1@Green-Frog ~ % java Test1 1
user1@Green-Frog ~ % echo $?     
0
user1@Green-Frog ~ % java Test1 -1
user1@Green-Frog ~ % echo $?      
2
user1@Green-Frog ~ % java Test1 15
user1@Green-Frog ~ % echo $?      
1
user1@Green-Frog ~ %

On Linux, BSD, OSX, etc. you can check the exit status like this:


echo Exit code is $?

On Windows (cmd.exe) you can check the exit status like this:


echo Exit code is %errorlevel%

You should be able to use the following in PowerShell:


Write-Host "Exit code is $lastExitCode"