开发者

difference between System.exit(0) and System.exit(-1) [duplicate]

开发者 https://www.devze.com 2023-03-26 07:00 出处:网络
This question already has answers here: Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java
This question already has answers here: Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java (12 answers) Closed 7 years ago.

Can any one share to me difference between System.exit(0) and System.exit(-1) it开发者_如何转开发 is helpful if you explain with example.


It's just the difference in terms of the exit code of the process. So if anything was going to take action based on the exit code (where 0 is typically success, and non-zero usually indicates an error) you can control what they see.

As an example, take this tiny Java program, which 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 running it from a bash shell, where && means "execute the second command if the first one is successful" we can have:

~ $ java Test && echo Success!
Success!

~ $ java Test boom && echo Success!


System.exit(0) means it is a normal exit from a program.But System.exit(-1) means the exit may be due to some error. Any number other that zero means abnormal exit.


The parameter of System.exit(int) 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 inidaces that something went wrong.


If you run your Java program in Linux/Unix you can examine the result using echo $? command. This is why it is important to call System.exit(0) (this is done for you if you don't) if everything is fine and System.exit(non-zero) otherwise.

0

精彩评论

暂无评论...
验证码 换一张
取 消