gpt4 book ai didi

java - 当用户只想打印用法时,如何避免所需选项的 ParserException?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:13 24 4
gpt4 key购买 nike

所以我有一个 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"));

如果 seq1seq2 不存在,当我调用 parser.parse(args) 时抛出异常 - 但我想要它打印我的消息并且没有抛出异常 - 怎么办?这自然会在 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);
}

最佳答案

改编自 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);

如果出现更优雅的东西,我会很乐意接受

关于java - 当用户只想打印用法时,如何避免所需选项的 ParserException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com