This question already has answers here:
What does the Java assert keyword do, and when should it be used?

(19个回答)


3年前关闭。



assert是做什么的?
例如在函数中:
private static int charAt(String s, int d) {
    assert d >= 0 && d <= s.length();
    if (d == s.length()) return -1;
    return s.charAt(d);
}

最佳答案

如果您使用-enableassertions(或简称-ea)启动程序,则此语句

assert cond;

相当于
if (!cond)
    throw new AssertionError();

如果不使用此选项启动程序,则assert语句将无效。

例如,问题中发布的assert d >= 0 && d <= s.length();等效于
if (!(d >= 0 && d <= s.length()))
    throw new AssertionError();

(如果使用-enableassertions启动。)

形式上,Java Language Specification: 14.10. The assert Statement表示以下内容:



如果使用-ea开关控制“启用或禁用”,而“报告错误”则表示抛出了AssertionError

最后,assert一个鲜为人知的功能:

您可以像这样附加: "Error message":
assert d != null : "d is null";

指定应该抛出什么AssertionError的错误消息。

这篇文章已被重写为here文章。

09-25 17:51
查看更多