16. IllegalArgumentException是什么?什么时候会抛出这个异常?
大约 2 分钟
什么是IllegalArgumentException
?
IllegalArgumentException
是Java中的一种非受检异常(Unchecked Exception
),它继承自RuntimeException
。当一个方法接收到不合法或不合适的参数时,通常会抛出这个异常。与其相关的错误一般是在调用方传递了不符合预期的参数(如null
值、不在合法范围内的数值等)时产生的。
IllegalArgumentException
的使用场景
IllegalArgumentException
通常在以下情况下抛出:
参数值不在预期范围内:
- 当方法需要特定范围内的数值,而传递的参数超出了这个范围,通常会抛出
IllegalArgumentException
。
public void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException("Age must be between 0 and 150."); } this.age = age; }
- 当方法需要特定范围内的数值,而传递的参数超出了这个范围,通常会抛出
传递
null
参数:- 当方法明确要求非
null
参数,但调用方却传递了null
,通常会抛出IllegalArgumentException
。
public void setName(String name) { if (name == null) { throw new IllegalArgumentException("Name cannot be null."); } this.name = name; }
- 当方法明确要求非
参数类型不匹配:
- 虽然Java的类型系统能够防止大多数类型不匹配的情况,但在某些动态操作或反射机制中,如果传递了不匹配的类型参数,也可能抛出
IllegalArgumentException
。
public void setObject(Object obj) { if (!(obj instanceof String)) { throw new IllegalArgumentException("Expected a String object."); } // 继续处理 }
- 虽然Java的类型系统能够防止大多数类型不匹配的情况,但在某些动态操作或反射机制中,如果传递了不匹配的类型参数,也可能抛出
传递不合法的枚举值:
- 如果方法要求特定的枚举值,而调用方传递了非枚举的值或
null
,则可能抛出IllegalArgumentException
。
public enum Direction { NORTH, SOUTH, EAST, WEST } public void setDirection(Direction direction) { if (direction == null) { throw new IllegalArgumentException("Direction cannot be null."); } // 继续处理 }
- 如果方法要求特定的枚举值,而调用方传递了非枚举的值或
示例代码
public class IllegalArgumentExceptionExample {
public static void main(String[] args) {
try {
setAge(-5); // 传递非法参数
} catch (IllegalArgumentException e) {
System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
}
try {
setName(null); // 传递null参数
} catch (IllegalArgumentException e) {
System.out.println("Caught an IllegalArgumentException: " + e.getMessage());
}
}
public static void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("Age must be between 0 and 150.");
}
}
public static void setName(String name) {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null.");
}
}
}
输出结果
Caught an IllegalArgumentException: Age must be between 0 and 150.
Caught an IllegalArgumentException: Name cannot be null.
什么时候使用IllegalArgumentException
?
- 当方法对传递的参数有特定的要求,而调用方传递的参数不符合这些要求时。
- 需要明确告知调用方参数的问题,并且这种错误是由不正确的使用方法引起的,而不是方法本身的问题。
- 在方法内部做参数验证,并且发现参数不合法时,使用
IllegalArgumentException
可以快速定位问题的原因。
总结
IllegalArgumentException
是Java中用于表示方法传入了不合法或不合适参数的异常。当参数的值不在合法范围内、类型不匹配或不应为null
时,可以使用此异常。合理使用IllegalArgumentException
可以帮助你编写更加健壮和防御性强的代码,避免在运行时遇到无法预料的错误。