什么是“断言”?关键字吗? [英] What does the "assert" keyword do?

查看:857
本文介绍了什么是“断言”?关键字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

断言做什么?
例如在函数中:

What does assert do? For example in the function:

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 简称)然后这句话

If you launch your program with -enableassertions (or -ea for short) then this statement

assert cond;

相当于

if (!cond)
    throw new AssertionError();

如果在没有此选项的情况下启动程序,则assert语句将无效。

If you launch your program without this option, the assert statement will have no effect.

例如,断言d> = 0&& d< = s.length(); ,如您的问题中所述,相当于

For example, assert d >= 0 && d <= s.length();, as posted in your question, is equivalent to

if (!(d >= 0 && d <= s.length()))
    throw new AssertionError();

(如果您使用 -enableassertions 推出是。)

(If you launched with -enableassertions that is.)

正式来说, Java语言规范:14.10。 断言声明说明如下:

Formally, the Java Language Specification: 14.10. The assert Statement says the following:


14.10。 断言陈述

断言是断言包含布尔表达式的语句。断言启用或禁用。如果断言已启用,则断言的执行将导致布尔表达式的评估,如果表达式求值为 false ,则报告错误。如果断言被禁用,则断言的执行不会产生任何影响。

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 <抛出/ code>。

Where "enabled or disabled" is controlled with the -ea switch and "An error is reported" means that an AssertionError is thrown.

您可以附加:错误消息,如下所示:

You can append : "Error message" like this:

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

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

to specify what the error message of the thrown AssertionError should be.

此帖已被重写为文章这里

这篇关于什么是“断言”?关键字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆