assert不能替代illegalargumentexception,因其默认关闭、抛出assertionerror(属error而非runtimeexception),且仅适用于开发/测试阶段内部不变量校验;而illegalargumentexception是强制、可捕获的运行时校验,用于方法入口参数合法性检查。

Java 中的 assert 是 JVM 提供的断言机制,默认是关闭的,仅用于开发/测试阶段的调试检查,**不会在生产环境抛出 IllegalArgumentException**。若需在参数不合法时明确抛出 IllegalArgumentException,应使用显式条件判断 + 手动抛异常,而不是依赖 assert。
为什么 assert 不能替代 IllegalArgumentException
assert 在运行时默认禁用(需加 -ea 参数开启),且其失败抛出的是 AssertionError(继承自 Error),不是 RuntimeException 的子类 IllegalArgumentException。API 设计规范要求对非法参数应抛出 IllegalArgumentException,这是调用方可以合理捕获和处理的预期行为。
正确做法:手动校验 + 显式抛异常
在方法入口对参数做空值、范围、状态等校验,不满足条件时立即抛出 IllegalArgumentException:
- 使用
Objects.requireNonNull()检查 null(适用于非基本类型) - 用普通
if判断数值范围、集合大小、字符串长度等 - 推荐搭配 Guava 的
Preconditions或 Spring 的Assert工具类,语义更清晰
示例:
public void process(String name, int age) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("name must not be null or blank");
}
if (age 150) {
throw new IllegalArgumentException("age must be between 0 and 150");
}
// 正常逻辑...
}
可选增强:使用工具类简化写法
避免重复写 if-throw,提高可读性:
-
Guava:
Preconditions.checkArgument(age > 0, "age must be positive") -
Spring Framework:
Assert.notNull(name, "name must not be null") -
Apache Commons Lang:
Validate.notBlank(name, "name must not be blank")
这些工具内部仍是通过 if 判断后抛 IllegalArgumentException,但封装了常用校验场景。
什么时候可以用 assert?
assert 适合验证程序内部不变量(如私有方法的中间状态、算法前提条件),且该条件在正常执行路径中“理论上绝不会为 false”。例如:
private int computeIndex() {
int idx = someCalculation();
assert idx >= 0 && idx
<p>注意:这类断言不用于用户输入或外部参数校验,也不应作为业务逻辑的合法性保障。</p>Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











