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.
Code
// 三个约定退出码: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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.