IllegalArgumentException用于参数校验,当传入参数不合法时抛出,如null值、数值越界、字符串格式错误等,可通过throw new IllegalArgumentException("消息")主动抛出,并推荐使用Objects.requireNonNull简化null检查,提升代码健壮性与可读性。
在Java中,IllegalArgumentException 是一个非受检异常(unchecked exception),常用于方法参数校验时抛出,表示传入的参数不合法或不符合预期。通过主动抛出这个异常,可以提高代码的健壮性和可读性。
何时使用 IllegalArgumentException
当方法接收到不符合业务逻辑或约束条件的参数时,应立即中断执行并提示调用方问题所在。例如:
- 参数为 null,但不允许为空
- 数值超出合理范围(如年龄为负数)
- 字符串为空或格式错误
- 集合为空但要求非空
如何手动抛出 IllegalArgumentException
可以直接使用 throw new IllegalArgumentException("错误信息") 来抛出异常,并附带清晰的描述信息。
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("年龄必须在0到150之间,实际值:" + age);
}
this.age = age;
}
常见的参数校验场景与写法
以下是一些典型校验示例:
// 校验对象非null
public void processUser(User user) {
if (user == null) {
throw new IllegalArgumentException("用户对象不能为null");
}
// 处理逻辑
}
// 校验字符串非空
public void setName(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("姓名不能为空");
}
this.name = name.trim();
}
// 校验集合非空
public void addScores(List scores) {
if (scores == null || scores.isEmpty()) {
throw new IllegalArgumentException("成绩列表不能为空");
}
this.scores.addAll(scores);
}
使用 Objects.requireNonNull 简化 null 校验
Java 7+ 提供了 Objects.requireNonNull 方法,可用于简化 null 判断。
import java.util.Objects; public void setEmail(String email) { Objects.requireNonNull(email, "邮箱地址不能为null"); if (!email.contains("@")) { throw new IllegalArgumentException("邮箱格式不正确: " + email); } this.email = email; }
基本上就这些。合理使用 IllegalArgumentException 能让方法契约更清晰,帮助调用者快速发现和修复问题。关键是提供有意义的错误消息,说明“哪里错了”以及“期望是什么”。









