I would like to have a printed usage help message, when an option which is specified as a program argument is not valid (not available in the 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 a parameter the 'Test' string. I was thinking, that invalid options cause the parser to throw ParseException, however they do not. How can I achieve that behaviour? Is it possible with this library at all? Now it just omits parameters which are not valid.
UPDATE Actually it throws exception when option has a '-' prefix. So '-Test' cause throwing an exception, but 'Test' does not. My question anyway is still valid, how to force parser to throw an exception on an invalid parameter.
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
.