Search code examples
javaapache-commons-cli

How can I avoid a ParserException for required options when user just wants to print usage?


So I have an Options instance which among other options has (notice the 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"));

When I call parser.parse(args) throws an exception if seq1 and seq2 are not present - but I want to have it print my message and no exception thrown - how to go about it ? This throws NPE in line.hasOption("help"), naturally :

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);
}

Solution

  • Solution adapted from here

    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);
    

    If anything more elegant comes up I would gladly accept it