Artur Skrzydło Artur Skrzydło - 1 month ago 8
Java Question

Why default parser (using commons-cli) does not throw exception when option is not recognized?

I would like to have a printed usage help message, when option which is specified as an program argument is not valid (not available in predefined options list).

CommandLineParser parser = new BasicParser();
try {
CommandLine line = parser.parse(getOptions(), args);
}
catch( ParseException exp ) {
getLogger().info("Invalid command line option name. "+exp.getMessage());
HelpFormatter hf = new HelpFormatter();
hf.printHelp("destDir", getOptions());
return false;
}
return true;


I type as an parameter 'Test' string. I was thinking, that invalid options cause parser to throw ParseException, however it's not. How can I achieve that behaviour ? Is it possible with this library at all ? Now it just ommit paremeters which are not valid.

UPDATE
Actually it throws exception when option has a '-' prefix. So '-Test' cause throwing exception, but 'Test' not. My question anyway is still valid, how to force parser to throw exception on invalid parameter

Answer

Command lines have two types of entry other than the program name, Options (which are specified with a - or --) and what I will call parameters (which probably have a better name but I don't know what it is!) which don't have a prefix. For example, for ls:

ls -la foo

The options are -l and -a, and parameter is foo (the directory to list). When you parse a command line with commons-cli it only cares about the options, it ignores everything else. Which is why it doesn't fail if you add Test (not an option) but does if you add -Test.