检查要添加到选项的值是否有效,如果无效,则手动抛出异常。可以使用以下示例代码:
// 创建选项 Options options = new Options(); Option ageOption = new Option("age", true, "age of person"); // 将选项添加到选项组 options.addOption(ageOption);
// 解析命令行参数 CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); // 获取年龄值 String ageValue = cmd.getOptionValue("age"); // 检查年龄值是否有效 if (Integer.parseInt(ageValue) <= 0) { throw new IllegalArgumentException("Age should be greater than zero."); } // 使用年龄值进行进一步操作 } catch (ParseException e) { System.err.println("Error while parsing command line arguments: " + e.getMessage()); } catch (IllegalArgumentException e) { System.err.println("Invalid argument: " + e.getMessage()); }
在这个示例代码中,我们检查了年龄值是否为正数,如果无效,则手动抛出了IllegalArgumentException异常。这样,即使Commons CLI没有抛出异常,我们也可以通过代码来处理无效参数。