# 断言的概念
断言机制允许在测试期间向代码插入一些检查语句,当代码发布时,这些插入的检测语句将会被自动地移走。
断言形式: assert 条件;
和 assert 条件:表达式;
# 启用和禁用断言
启用断言命令: enableassertions
或 -ea
。
禁用断言命令: disableassertions
或 -da
。
# IDEA 使用断言
配置 VM options 为 - ea。
代码中加入断言。
public class Test {
public static int add(int a, int b) {
// return a + b;
return -1; // 程序出错返回 - 1
}
public static void main(String[] args) {
int c = add(1, 2);
assert c > 0;
System.out.println(c);
}
}
运行结果。
Exception in thread "main" java.lang.AssertionError at com.example.demo.test.Test.main(Test.java:16)