The difference between System.exit (0) and System.exit (-1)

Can someone share me the difference between System.exit(0) and System.exit(-1) , it is useful if you explain with an example.

+6
source share
4 answers

This is just the difference in terms of the process exit code. Therefore, if something acts on the exit code (where 0 is usually successful, and a nonzero value usually indicates an error), you can control what they see.

As an example, take this tiny Java program that uses the number of command line arguments as the exit code:

 public class Test { public static void main(String[] args) throws Exception { System.exit(args.length); } } 

Now run it from the bash shell, where && means "execute the second command if the first is successful", we can:

 ~ $ java Test && echo Success! Success! ~ $ java Test boom && echo Success! 
+16
source

System.exit (0) means that this is a normal exit from the program. But System.exit (-1) means that the output may be caused by some error. Any number equal to zero means an abnormal output.

+3
source

The System.exit (int) parameter is the return value of your program, which can be evaluated in batch jobs (usually for console programs). By convention, every value other than 0 means that something went wrong.

0
source

If you run your Java program on Linux / Unix, can you check the result with the echo $? command echo $? . This is why it is important to call System.exit(0) (this is done for you if you do not), if everything is fine and System.exit(non-zero) otherwise.

0
source

Source: https://habr.com/ru/post/894255/


All Articles