Java中的System.exit()

The System.exit() method terminates the Java virtual machine. This method takes an argument, which is the status code passed to the caller.

System.exit()方法终止Java虚拟机。 此方法采用一个参数,这是传递给调用方的状态代码。

A status code of zero signifies a normal exit whereas a status code of non-zero signifies an abnormal code.

状态代码为零表示正常退出,而状态代码为非零表示异常代码。

The code is not so important within Java itself. However, it’s common for scripts to rely on the exit codes of commands it invokes.

在Java本身中,代码并不是那么重要。 但是,脚本通常依赖于它调用的命令的退出代码。

Several non-zero codes can mean several different types of exits. This enables programmers to design their response system accordingly.

几种非零代码可能意味着几种不同类型的出口。 这使程序员可以相应地设计其响应系统。

The System.exit() is like a harsh version of breaking out of loops using conditionals.

System.exit()类似于使用条件语句打破循环的严酷版本。

System.exit(),状态码为0 (System.exit() with status code 0)

Let’s write a for loop and use System.exit(0) to exit out of the program with a status code of 0.

让我们编写一个for循环,并使用System.exit(0)以状态代码0退出程序。


public class Main {

    public static void main(String[] args) {

        for(int i=0;i<10;i++){
            System.out.println(i);
            if(i>5){
                System.exit(0);
            }
        }
    }
}
System Exit Code 0
Output
输出量

0
1
2
3
4
5
6

Process finished with exit code 0

We can see that the program terminates with an exit code of 0.

我们可以看到程序以退出代码0终止。

以非零状态码退出 (Exiting with a non-zero status code )

We can exit out of the program with any non zero exit code.

我们可以使用任何非零的退出代码退出程序。


public class Main {

    public static void main(String[] args) {

        for(int i=0;i<10;i++){
            System.out.println(i);
            if(i>5){
                System.exit(10);
            }
        }
    }
}
System Code Non Zero

You can see that the exit code is printed as 10 in the output.

您可以看到出口代码在输出中显示为10。

何时使用System.exit() (When to use System.exit())

It’s useful when you are calling a Java program from shell script. You can terminate the program in case of an abnormal scenario and pass on the status code to the caller shell script.

从外壳程序脚本调用Java程序时,此功能很有用。 您可以在异常情况下终止程序,并将状态代码传递给调用方外壳脚本。

结论 (Conclusion )

That is how Java.lang.System.exit() works. It is common to use it to exit loops and functions. Interestingly enough, System.exit() if not placed properly can render a certain portion of your code unreachable.

这就是Java.lang.System.exit()的工作方式。 通常使用它退出循环和功能。 有趣的是,如果未正确放置System.exit(),可能会使代码的某些部分无法访问。

翻译自: https://www.journaldev.com/41960/system-exit-in-java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值