当用户只想打印使用情况时,如何避免所需选项的ParserException?

Mr_*_*s_D 7 java apache-commons-cli

所以我有一个Options实例,其中包括其他选项(注意isRequired()):

        options.addOption(OptionBuilder
                .withLongOpt("seq1")
                .withDescription("REQUIRED : blah blah")
                .hasArg().isRequired().create());
        options.addOption(OptionBuilder
                .withLongOpt("seq2")
                .withDescription("REQUIRED : blih blih")
                .hasArg().isRequired().create());
        options.addOption(new Option("?", "help", false,
                "print this message and exit"));
Run Code Online (Sandbox Code Playgroud)

当我调用parser.parse(args)抛出异常时,如果seq1seq2不存在 - 但我希望它打印我的消息并且没有异常抛出 - 如何去做?这line.hasOption("help")自然会引入NPE :

CommandLine line = null;
try {
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    line = parser.parse(options, args);
} catch (ParseException e) {
    if (line.hasOption("help")) { //NPE
        usage(0);
    }
    System.err.println("Parsing failed.  Reason: " + e.getMessage());
    usage(1);
}

private static void usage(int exitCode) {
    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("Smith Waterman", OPTIONS, true);
    System.exit(exitCode);
}
Run Code Online (Sandbox Code Playgroud)

Mr_*_*s_D 7

解决方案从这里改编

private static final Options OPTIONS = new Options();
private static final Options HELP_OPTIONS = new Options();
OPTIONS.addOption(OptionBuilder
        .withLongOpt("seq1")
        .withArgName("file1")
        .withDescription(
                "REQUIRED : the file containing sequence 1")
        .hasArg().isRequired().create());
// etc
final Option help = new Option("?", "help", false,
        "print this message and exit");
HELP_OPTIONS.addOption(help);
OPTIONS.addOption(help);
// later
CommandLineParser parser = new GnuParser();
CommandLine line = parser.parse(HELP_OPTIONS, args, true); // true so it
// does not throw on unrecognized options
if (line.hasOption("help")) {
    usage(0); // calls exit
}
line = parser.parse(OPTIONS, args);
Run Code Online (Sandbox Code Playgroud)

如果有任何更优雅的东西出现,我很乐意接受它