当前位置:   article > 正文

如何解决 Java 中的 IllegalArgumentException 异常?_java.langillegalar

java.langillegalar

非法参数异常(IllegalArgumentException)的抛出是为了表明一个方法被传递了一个非法参数。该异常扩展了 RuntimeException 类,因此属于在 Java 虚拟机(JVM)运行期间可能抛出的异常。它是一种未检查异常,因此不需要在方法或构造函数的 throws 子句中声明。

出现 java.lang.IllegalArgumentException 的原因

  • 当参数超出范围时。例如,百分比应介于 1 到 100 之间。如果用户输入的是 101,则将抛出 IllegalArugmentExcpetion。
  • 参数格式无效时。例如,如果我们的方法需要 YYYY/MM/DD 这样的日期格式,但如果用户传递的是 YYYY-MM-DD。那么我们的方法就无法理解,就会抛出 IllegalArugmentExcpetion。
  • 当一个方法需要非空字符串作为参数,但传递的却是空字符串时。

示例

public class Student {
   int m;
   public void setMarks(int marks) {
      if(marks < 0 || marks > 100)
         throw new IllegalArgumentException(Integer.toString(marks));
      else
         m = marks;
   }
   public static void main(String[] args) {
      Student s1 = new Student();
      s1.setMarks(45);
      System.out.println(s1.m);
      Student s2 = new Student();
      s2.setMarks(101);
      System.out.println(s2.m);
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

输出

45
Exception in thread "main" java.lang.IllegalArgumentException: 101
	at Student.setMarks(Student.java:5)
	at Student.main(Student.java:14)
  • 1
  • 2
  • 3
  • 4

解决 IllegalArgumentException 的步骤

  • 当抛出 IllegalArgumentException 时,我们必须检查 Java 堆栈跟踪中的调用堆栈,找出产生错误参数的方法。
  • IllegalArgumentException 非常有用,可用于避免应用程序的代码必须处理未经检查的输入数据的情况。
  • IllegalArgumentException 的主要用途是验证来自其他用户的输入。
  • 如果要捕获 IllegalArgumentException,我们可以使用 try-catch 块。通过这样做,我们可以处理某些情况。假设我们在 catch 代码块中加入代码,让用户有机会再次输入,而不是停止执行,尤其是在循环的情况下。

示例

import java.util.Scanner;
public class Student {
   public static void main(String[] args) {
      String cont = "y";
      run(cont);
   }
   static void run(String cont) {
      Scanner scan = new Scanner(System.in);
      while( cont.equalsIgnoreCase("y")) {
         try {
            System.out.println("Enter an integer: ");
            int marks = scan.nextInt();
            if (marks < 0 || marks > 100)
               throw new IllegalArgumentException("value must be non-negative and below 100");
            System.out.println( marks);
         } catch(IllegalArgumentException i) {
            System.out.println("out of range encouneterd. Want to continue");
            cont = scan.next();
            if(cont.equalsIgnoreCase("Y"))
               run(cont);
         }
      }
   }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

输出

Enter an integer:
1
1
Enter an integer:
100
100
Enter an integer:
150
out of range encouneterd. Want to continue
y
Enter an integer:
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/214070
推荐阅读
相关标签
  

闽ICP备14008679号