【问题标题】:Throw an exception when too many/few arguments are passed to main当传递给 main 的参数过多/过少时抛出异常
【发布时间】:2014-02-17 08:50:40
【问题描述】:

我正在编写一个掷骰子程序,它有两个参数传递给主程序,骰子有多少面以及你想扔它的次数。如果传递的参数少于或多于两个,我想抛出异常。我该怎么做呢?

我找到了this。 但我不确定如何使用它?当然,在抛出异常之前,我必须以某种方式指定预期的参数数量吗?

【问题讨论】:

    标签: java exception arguments main args


    【解决方案1】:

    试试这个:

    public class Dice {
      public static void main(String... args) {
    
        // First, ensure there are 2 args
        if (args.length != 2) {
          throw new IllegalArgumentException("Exactly 2 parameters required !");
        }
    
        int firstArgInt;
        int secondArgInt;
    
        // Verify all args are integers
        try {
          firstArg = Integer.parseIng(args[0]);
        } catch (NumberFormatException nbfe) {
          // 2 possible solutions : throw an exception, or assign a default value
          // - throw new IllegalArgumentException("First arg must be an integer");
          // - firstArg = 42;
        }
        try {
          secondArg = Integer.parseIng(args[1]);
        } catch (NumberFormatException nbfe) {
          // Same as above
        }
    
        // Etc.
    
      }
    }
    

    【讨论】:

    • 谢谢,但是如果我知道要检查参数是否为数字,我会怎么做?我想抛出一个不同的异常来捕获和处理,但是如果我的 catch 块捕获 IllegalArgumentException 它不知道如何处理,因为它是相同类型的异常?
    • 我编辑了答案以添加 args 类型转换。如果参数不是 int,您可能希望为其分配默认值而不是引发异常。
    • 我尝试以相同的方式向您创建的第一个异常添加另一个异常,它开始抛出以下错误:找不到符号 throw new IncorrectInputException ^ 我在下面包含了我的代码 try { noOfFaces = Integer .parseInt(args[0]); if (noOfFaces
    • 首先,parseInt() 方法抛出一个 NumberFormatException 是它的参数不代表一个数字,所以你真的应该首先捕获这个异常。然后,只有到那时,您才能测试您的数字是否小于 2,并采取任何适当的措施,例如抛出异常。我看到您使用IncorrectInputException,这是您编写的自定义异常吗?我建议坚持我在上面的示例代码中使用的标准 IllegalArgumentException
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2016-07-21
    • 2016-12-18
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多