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 d >= 0 && d <= s.length();
,正如您在问题中发布的那样,相当于
if (!(d >= 0 && d <= s.length()))
throw new AssertionError();
(如果您使用 -enableassertions
启动。)
正式地,Java Language Specification: 14.10. The assert
Statement说如下:
14.10. The
assert
Statement
An assertion is anassert
statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates tofalse
. If the assertion is disabled, execution of the assertion has no effect whatsoever.
“启用或禁用” 由 -ea
控制。开关和“报告错误” 表示 AssertionError
被抛出。
最后,assert
的一个鲜为人知的特性:
您可以附加 : "Error message"
像这样:
assert d != null : "d is null";
指定抛出的 AssertionError 的错误信息应该是什么。
本帖已改写为文章 here .
关于java - "assert"关键字有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3018683/