在 Java 里,Assert(断言)本身不是“调试工具”,而是一种程序正确性检查机制。它主要用来在开发/测试阶段快速发现“不该发生的情况”。要“用 Assert 定位问题”,关键在怎么用、怎么看错误信息、以及配合调试手段。
下面分几块说清楚。
assert condition;
// 或
assert condition : "错误信息";
默认是关闭的!
java -ea MyApp
# 或
java -enableassertions MyApp
关闭时,assert 语句完全不执行,也不会报错。
这是最常见的定位方式。
public void setName(String name) {
assert name != null : "name must not be null";
this.name = name;
}
如果传入 null:
Exception in thread "main" java.lang.AssertionError: name must not be null
➡ 问题位置直接指向 setName 方法
switch (type) {
case A: ...
case B: ...
default:
assert false : "unexpected type: " + type;
}
一旦进入 default:
AssertionError: unexpected type: C
➡ 立刻知道:是哪个枚举值没处理
assert list.size() == expectedSize :
"size mismatch: " + list.size() + " != " + expectedSize;
适合定位:
❌ 不好:
assert x > 0;
✅ 好:
assert x > 0 : "x should be positive but was " + x;
➡ 不用打断点就能知道现场数据
AssertionError 会给出:
at com.demo.Service.process(Service.java:42)
➡ 直接跳到那一行
-ea// 错误示例
public void save(User u) {
assert u != null; // 生产可能关掉
}
✅ 正确做法:
if (u == null) {
throw new IllegalArgumentException("user is null");
}
Assert 只用于“程序逻辑错误”,不用于“用户输入错误”
Assert 定位问题的核心思路:
如果你愿意,可以把:
贴出来,我可以直接帮你分析是哪一步逻辑出了问题。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。