Exit Codes For CLI Errors

Follow the CLI exit-code convention: zero for success, one for business failures, two for usage errors, with diagnostics written to stderr.

JavaCli Tooling

Code

snippet
// 三个约定退出码:0 成功 / 1 业务失败 / 2 用法错误
// java DeployTool.java prod api  -> "deploying to prod",退出码 0
// java DeployTool.java bogus     -> "unknown env: bogus",退出码 1
// java DeployTool.java           -> usage 行,退出码 2
public class DeployTool {

    public static void main(String[] args) {
        if (args.length == 0) {
            // 用法错误写 stderr:调用脚本靠退出码分支,不解析正文
            System.err.println("usage: DeployTool <env> [service...]");
            System.exit(2);
        }
        String env = args[0];
        if (!env.equals("staging") && !env.equals("prod")) {
            System.err.println("unknown env: " + env);
            System.exit(1);
        }
        System.out.println("deploying to " + env);
        // 正常返回即退出码 0
    }
}

How the snippet works

Everything happens inside the class DeployTool and the function main.

What to watch for

  • Where imports appear at all, they are standard-library modules.

Applying it

Entry signature: public static void main(String[] args)

Look for the deploying to prefixes when the file runs; they tie each line to its step.

Statements that matter

String env = args[0];
System.exit(2);
System.exit(1);

Interactive Tools for This Topic

FAQ

What does Exit Codes For CLI Errors print when run?
No setup needed: run the file and look for labeled lines like `deploying to` in the output.