307

I'd like to know the difference between the following in Java

System.exit(0);
System.exit(-1);
System.exit(1);

When do I have to use the above code appropriately?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
giri
  • 26,773
  • 63
  • 143
  • 176
  • 20
    why didn't you mark the answer as the 'best answer' so there is a green tick? it helps other people know what the best one is!! – Saksham Goyal Dec 18 '16 at 11:55

12 Answers12

269

The parameter of exit should qualify if the execution of the program went good or bad. It's a sort of heredity from older programming languages where it's useful to know if something went wrong and what went wrong.

Exit code is

  • 0 when execution went fine;
  • 1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.

If I'm correct exit codes used to be just positive numbers (I mean in UNIX) and according to range:

  • 1-127 are user defined codes (so generated by calling exit(n))
  • 128-255 are codes generated by termination due to different unix signals like SIGSEGV or SIGTERM

But I don't think you should care while coding on Java, it's just a bit of information. It's useful if you plan to make your programs interact with standard tools.

RubioRic
  • 2,442
  • 4
  • 28
  • 35
Jack
  • 131,802
  • 30
  • 241
  • 343
  • 35
    Also note that an exit code of 0 counts as true in the shell and any other code counts as false. So `java MyApp && echo success` will print "success" iff MyApp has an exit code of 0, i.e. if it calls `exit(0)` or simply reaches the end of the main method without an error. – sepp2k Mar 12 '10 at 17:41
  • 20
    Please, always care for the exit code if your app can be used in a script. It is very annoying to have a tool failing silently in the middle of your script (or printing some stack trace and exiting with 0). – Doncho Gunchev Mar 14 '14 at 11:51
  • 6
    One thing to note: when returning -1, the largest possible positive number is returned in unsigned context (in two's complement representation -1 always sets all bits regardless of number of bytes in the number). So -1 is usually returned when you're returning a non-specific error and don't want it to clash with possible error codes that are already defined and documented. e.g. error code 1 might have been documented as write error; error code 2 might be read error, etc. – Nylon Smile Mar 20 '14 at 01:38
  • It's a 'sort of heredity' from Unix's *exit(2)` actually. – user207421 Mar 03 '17 at 04:09
142

Zero => Everything Okay

Positive => Something I expected could potentially go wrong went wrong (bad command-line, can't find file, could not connect to server)

Negative => Something I didn't expect at all went wrong (system error - unanticipated exception - externally forced termination e.g. kill -9)

(values greater than 128 are actually negative, if you regard them as 8-bit signed binary, or twos complement)

There's a load of good standard exit-codes here

catch23
  • 17,519
  • 42
  • 144
  • 217
robert
  • 4,612
  • 2
  • 29
  • 39
  • 16
    "Something I expected to go wrong went wrong" sounds like "Everything Okay". – tobe Jan 15 '14 at 02:23
  • "Things that I as the developer can be reasonably expected to anticipate" User Error vs System Error; This is actually covered by top poster: values 128-255 are -ve wrt 8-bit signed binary. – robert Jan 20 '14 at 08:58
  • 7
    @tobe It's really more like "Something I expected **could** go wrong went actually wrong" ;) – Marcel Hernandez Jul 09 '14 at 08:55
  • 1
    Bash treats exit codes as 8-bit unsigned, and will mod 256, so a -1 becomes 255 and 256 becomes 0. Signals (in a kill, e.g. `kill -15`) often result in exit code `128+signal`, but (aside from 9) can be handled and return a different exit code. The `-` in `kill -15` is marks the number as a signal and not a pid, it does not make the signal negative. – Matthew Mar 04 '17 at 14:56
  • When you do `System.exit(-1)` and then in your shell `echo $?` you get '255'. This is why I said negative numbers are system errors, not because of the '-' in the kill parameter. *Did you seriously think that's what I thought?* But thank you for explaining the mechanism by which Bash constructs these codes. – robert Mar 08 '17 at 15:40
  • @robert I don't know if matthew thought that you thought that, but it might be nice info for those that actually thought that was the case or if they didn't know whether or not it was the case. – Rik Schaaf Jan 13 '18 at 09:25
  • @RikShaaf that's all well and good, but I was concerned that those that actually thought that his remark was right might have though I meant minus when I didn't and in that case what he thought was right was wrong and careless reader might think that I was wrong, thereby ending up being wrong themselves. – robert Jan 15 '18 at 10:09
58

System.exit(system call) terminates the currently running Java virtual machine by initiating its shutdown sequence. The argument serves as a status code.

By convention, a nonzero status code indicates abnormal termination.

  System.exit(0) or EXIT_SUCCESS;  ---> Success
  System.exit(1) or EXIT_FAILURE;  ---> Exception
  System.exit(-1) or EXIT_ERROR;   ---> Error

Read More at Java

On Unix and Linux systems, 0 for successful executions and 1 or higher for failed executions.

Premraj
  • 72,055
  • 26
  • 237
  • 180
11

A non-zero exit status code, usually indicates abnormal termination. if n != 0, its up to the programmer to apply a meaning to the various n's.

From https://docs.oracle.com/javase/7/docs/api/java/lang/System.html.

Vishnu Haridas
  • 7,355
  • 3
  • 28
  • 43
Frederik Wordenskjold
  • 10,031
  • 6
  • 38
  • 57
8

exit(0) generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value indicates unsuccessful termination in general.

clemens
  • 16,716
  • 11
  • 50
  • 65
Purushottam Sadh
  • 1,087
  • 10
  • 5
  • What cofuse me is the argument is passed by coder .Not a return value by the method.How can it indicate the termination result? – linjiejun Jul 20 '19 at 14:00
4

Here is the answer.

System.exit(0);// normal termination - Successful - zero
System.exit(-1);//Exit with some Error
System.exit(1);//one or any positive integer // exit with some Information message
Lova Chittumuri
  • 2,994
  • 1
  • 30
  • 33
2

A good gotcha is any error code > 255 will be converted to error code % 256. One should be specifically careful about this if they are using a custom error code > 255 and expecting the exact error code in the application logic. http://www.tldp.org/LDP/abs/html/exitcodes.html

nomad
  • 5,442
  • 1
  • 18
  • 8
1

System.exit(0) by convention, a zero status code indicates successful termination.

System.exit(1) -It means termination unsuccessful due to some error

androminor
  • 322
  • 1
  • 13
1

the difference of the numbers put in system.exit() is explained in other answers. but the REAL DIFFERENCE is that System.exit() is a code that gets returned to the invoking process. If the program is being invoked by the Operating system then the return code will tell the OS that if system.exit() returned 0 than everything was ok but if not something went wrong, then there could be some handlers for that in the parent process

parsa
  • 987
  • 2
  • 10
  • 23
0

As others answer 0 meaning success, otherwise.

If you using bat file (window) System.exit(x) will effect.

Code java (myapp):

if (error < 2){
    help();
    System.exit(-1);    
}
else{
    doSomthing();
    System.exit(0);
}

}

bat file:

java -jar myapp.jar
if %errorlevel% neq 0 exit /b %errorlevel%
rem -- next command if myapp is success --
nguyên
  • 5,156
  • 5
  • 43
  • 45
0

Look at the code below

public static void main(String[] args) {
    **String s=null;**
    try {
        System.out.println("Exit");
        System.exit(1);
        **s.length();**
    }catch(Exception e) {
        System.out.println("Exception");
    }finally {
        System.out.println("finally");
    }}

Here exit(0) : Generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination. No matter what you pass as an argument, the control flow always comes out and doesn't print anything next, either it may be catch block as s.length will throw exception here or finally

Asif
  • 3
  • 2
-10
class calc{
public static void main(String args[])
{
    int a, b, c;
    char ch;
    do{

        Scanner s=new Scanner(System.in);

                System.out.print("1. Addition\n");
                System.out.print("2. Substraction\n");
                System.out.print("3. Multiplication\n");
                System.out.print("4. Division\n");
                System.out.print("5. Exit\n\n");

                System.out.print("Enter your choice : ");
                ch=s.next().charAt(0);
                    switch (ch)
                    {
                        case '1' :
                        Addition chose1=new Addition();
                        chose1.add();
                        break;

                        case '2' :
                        Substraction chose2=new Substraction();
                        chose2.sub();
                        break;

                        case '3' :
                        Multiplication chose3= new Multiplication();
                        chose3.multi();
                        break;

                        case '4' :
                        Division chose4=new Division();
                        chose4.divi();
                        break;

                        case '5' :
                        System.exit(0);
                        break;

                        default :
                        System.out.print("wrong choice!!!");
                        break;
                    }
        System.out.print("\n--------------------------\n");                     
    }while(ch !=5); 
}

}

In the above code when its System.exit(0); and when i press case 5 it exits properly but when i use System.exit(1); and press case 5 it exits with error and again when i try with case 15 it exits properly by this i got to know that, when ever we put any int inside argument it specifies that, it take the character from that position i.e if i put (4) that it means take 5th character from that string if its (3) then it means take 4th character from that inputed string