非法参数异常(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); }}

输出

45Exception in thread "main" java.lang.IllegalArgumentException: 101at Student.setMarks(Student.java:5)at Student.main(Student.java:14)

解决 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); }} }}

输出

Enter an integer:11Enter an integer:100100Enter an integer:150out of range encouneterd. Want to continueyEnter an integer: