java - "assert"关键字有什么作用?

标签 java assert assertion

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 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 的一个鲜为人知的特性:

您可以附加 : "Error message"像这样:

assert d != null : "d is null";

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


本帖已改写为文章 here .

关于java - "assert"关键字有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3018683/

相关文章:

java - 在 Java 中使用 Key Vault 生成 SAS token

java - 带有 KeyCloak 的 Multi-Tenancy Quarkus?

c - 调试时断言错误

java - AssertionError - 虚数和实数加法器

c# - Rhino Mocks——断言不与模拟/ stub 交互

性能更好的 Java 序列化替代方案

java - Object.var-- 和 Object.var-=1 的区别?

c++ - Boost序列化断言失败

iphone - 游戏因NSLog错误而崩溃(cocos2d iPhone)

java - 这是在java中使用 volatile 变量的好例子吗?