Java assert 關鍵字
示例
使用 assert 測試表達式的真值
public class Main {
public static void main(String[] args) {
// Enable assertions
ClassLoader loader = ClassLoader.getSystemClassLoader();
loader.setDefaultAssertionStatus(true);
// Run the assert example
AssertExample example = new AssertExample();
example.run();
}
}
class AssertExample {
public void run() {
int a = 12;
try {
assert a == 12; // Assertion without a fail message
assert a == 12 : "a is not 12";
assert a == 15 : "a is not 15";
} catch (AssertionError e) {
System.out.println(e.getMessage());
}
}
}
定義和用法
assert
關鍵字評估一個布林表示式,如果該表示式評估結果為 false
,則丟擲 AssertionError
異常。當異常被丟擲時,我們稱斷言失敗。
可以新增一個可選表示式,如果斷言失敗,該表示式將用作異常訊息。
斷言預設是停用的。assert
語句除非啟用斷言,否則將被忽略。
斷言的目的是在除錯和測試程式時,清楚地標記程式在何時執行了意想不到的操作。