I am using args4j to parse the arguments given to my program.
Here is the code where I define 2 arguments of Date type. The handler just parses the given date and throws a CommandLineException if the date is malformed.
@Option(name="-b", metaVar="<beginDate>", handler=DateOptionHandler.class, usage="...")
private Date beginDate;
@Option(name="-e", metaVar="<endDate>", handler=DateOptionHandler.class, usage="...")
private Date endDate;
I need to be able to return a different code (int value) if it is beginDate or endDate which throws an exception.
Currently, my main method looks like this :
CmdLineParser parser = new CmdLineParser(this);
parser.setUsageWidth(120);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
/* Print usage if an error occurs during the parsing */
System.err.println(e.getMessage());
System.err.println("Usage : java LaunchProgram [options]");
e.getParser().printUsage(System.err);
/* What I need to do : */
if(optionWhichThrewTheException.equals("-b") return 2;
if(optionWhichThrewTheException.equals("-e") return 3;
/* Other arguments */
return -1;
}
But I can’t figure out how I can know which argument threw the exception (I looked the CmdLineException methods, but I found nothing).
Is there a way to obtain the parameter which can not be parsed ?
Thanks by advance for your help.
I’ve never used args4j, but looking at its documentation, it seems that the exception is thrown by the option handler. So, use a BDateOptionHandler and a EDateOptionHandler, that throw a custom subclass of CmdLineException containing the needed information: