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启动了.)
14.10. The assert Statement
An assertion is an assert 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 to false. If the assertion is disabled, execution of the assertion has no effect whatsoever.
使用-ea开关控制“启用或禁用”并且“报告错误”表示抛出AssertionError.
最后,一个鲜为人知的断言功能:
您可以附加:“错误消息”,如下所示:
assert d != null : "d is null";
指定抛出的AssertionError的错误消息应该是什么.
该帖子已被重写为第here条.
标签:assertion,java,assert
来源: https://codeday.me/bug/20190916/1806839.html