如何终止Java应用程序?

在应用程序中,有时我们希望终止应用程序的执行,例如因为找不到所需的资源。

要终止它,可以使用java.lang中的exit(status)方法。系统类或在java.lang。运行时类。当终止一个应用程序时,我们需要提供一个状态码,一个为任何异常终止分配的非零状态。

package org.nhooo.example.lang;

import java.io.File;

public class AppTerminate {
    public static void main(String[] args) {
        File file = new File("config.xml");

        int errCode = 0;
        if (!file.exists()) {
            errCode = 1;
        }

        // 当错误代码不为零时,终止
        if (errCode > 0) {
            System.exit(errCode);
        }
    }
}

对System.exit(status)的调用等于Runtime.getRuntime().exit(status)。实际上,System类将把终止过程委托给Runtime类。

运行代码会给出以下输出,因为找不到config.xml文件。

Process finished with exit code 1