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

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

问题描述

assert 有什么作用?例如在函数中:

private static int charAt(String s, int d) {断言 d >= 0 &&d <= s.length();如果 (d == s.length()) 返回 -1;返回 s.charAt(d);}

解决方案

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

assert cond;

相当于

if (!cond)抛出新的断言错误();

如果您在没有此选项的情况下启动程序,则断言语句将无效.

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

if (!(d >= 0 && d <= s.length()))抛出新的断言错误();

(如果您使用 -enableassertions 启动.)

<小时>

正式地,Java 语言规范: 14.10.assert 声明如下:

<块引用>

14.10.assert 声明
断言是包含布尔表达式的assert 语句.断言启用或禁用.如果启用了断言,则断言的执行会导致对布尔表达式进行评估,并且如果表达式的计算结果为 false,则会报告错误.如果断言被禁用,则断言的执行没有任何影响.

其中 启用或禁用"-ea 开关控制,报告错误" 表示 抛出断言错误.

<小时>

最后,assert 的一个鲜为人知的特性:

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

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

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

<小时>

这篇文章已被改写为一篇文章这里.>

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);
}

解决方案

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

assert cond;

is equivalent to

if (!cond)
    throw new AssertionError();

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

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();

(If you launched with -enableassertions that is.)


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

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.

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


And finally, a lesser known feature of assert:

You can append : "Error message" like this:

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

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


This post has been rewritten as an article here.

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

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