“断言”是什么?关键字做什么?

发布于 2024-09-05 04:24:59 字数 227 浏览 10 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

夏末 2024-09-12 04:24:59

如果您使用 -enableassertions (或简称 -ea)启动程序,那么此语句

assert cond;

相当于

if (!cond)
    throw new AssertionError();

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

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

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

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


正式地, Java 语言规范:14.10。 assert 语句 的内容如下:

14.10。 assert 语句
断言是包含布尔表达式的 assert 语句。断言可以启用或禁用。如果启用断言,则断言的执行会导致布尔表达式的计算,并且如果表达式计算结果为 false,则报告错误。如果断言被禁用,则断言的执行不会产生任何影响。

其中“启用或禁用”-ea开关和控制“报告错误”意味着抛出AssertionError


最后,assert 的一个鲜为人知的功能:

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

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

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

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.

記憶穿過時間隧道 2024-09-12 04:24:59

如果不满足条件,将抛出AssertionError

不过,必须启用断言;否则,assert 表达式不会执行任何操作。请参阅:

http://java.sun .com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable

If the condition isn't satisfied, an AssertionError will be thrown.

Assertions have to be enabled, though; otherwise the assert expression does nothing. See:

http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable

决绝 2024-09-12 04:24:59

assert 是一个调试工具,如果条件不成立,它会导致程序抛出 AssertionFailed 异常。在这种情况下,如果程序后面的两个条件中的任何一个计算结果为 false,则程序将引发异常。 一般来说,assert 不应该在生产代码中使用

assert is a debugging tool that will cause the program to throw an AssertionFailed exception if the condition is not true. In this case, the program will throw an exception if either of the two conditions following it evaluate to false. Generally speaking, assert should not be used in production code

画中仙 2024-09-12 04:24:59

尽管我已经阅读了很多有关此的文档,但我仍然对如何、何时以及在何处使用它感到困惑。

使其非常容易理解:

当您遇到类似的情况时,如下所示:

    String strA = null;
    String strB = null;
    if (2 > 1){
        strA = "Hello World";
    }

    strB = strA.toLowerCase(); 

您可能会收到警告(在 strB = strA.toLowerCase(); 上显示黄线),strA 可能会向 strB 生成 NULL 值。虽然你知道 strB 最终绝对不会为 null,但为了以防万一,你对

1 使用了断言。禁用警告。

2.如果发生最坏的情况(当您运行应用程序时),则抛出异常错误。

有时,当您编译代码时,您不会得到结果,这是一个错误。但应用程序不会崩溃,并且您会花费非常困难的时间来查找导致此错误的位置。

因此,如果你像这样放置断言:

    assert strA != null; //Adding here
    strB = strA .toLowerCase();

你告诉编译器 strA 绝对不是空值,它就可以“和平地”关闭警告。如果它是 NULL(最坏的情况发生),它将停止应用程序并向您抛出一个错误来定位它。

Although I have read a lot documentation about this one, I'm still confusing on how, when, and where to use it.

Make it very simple to understand:

When you have a similar situation like this:

    String strA = null;
    String strB = null;
    if (2 > 1){
        strA = "Hello World";
    }

    strB = strA.toLowerCase(); 

You might receive warning (displaying yellow line on strB = strA.toLowerCase(); ) that strA might produce a NULL value to strB. Although you know that strB is absolutely won't be null in the end, just in case, you use assert to

1. Disable the warning.

2. Throw Exception error IF worst thing happens (when you run your application).

Sometime, when you compile your code, you don't get your result and it's a bug. But the application won't crash, and you spend a very hard time to find where is causing this bug.

So, if you put assert, like this:

    assert strA != null; //Adding here
    strB = strA .toLowerCase();

you tell the compiler that strA is absolutely not a null value, it can 'peacefully' turn off the warning. IF it is NULL (worst case happens), it will stop the application and throw a bug to you to locate it.

街角迷惘 2024-09-12 04:24:59

使用此版本的断言语句来提供 AssertionError 的详细消息。系统将 Expression2 的值传递给相应的 AssertionError 构造函数,该构造函数使用该值的字符串表示形式作为错误的详细消息。

详细消息的目的是捕获和传达断言失败的详细信息。该消息应该允许您诊断并最终修复导致断言失败的错误。请注意,详细消息不是用户级错误消息,因此通常没有必要单独使这些消息易于理解或将其国际化。详细消息应在完整堆栈跟踪的上下文中结合包含失败断言的源代码进行解释。

JavaDoc

Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.

JavaDoc

不必了 2024-09-12 04:24:59

断言通常主要用作检查程序预期行为的一种手段。在大多数情况下,它应该会导致崩溃,因为程序员对程序状态的假设是错误的。这就是断言的调试方面的用武之地。它们创建了一个检查点,如果我们想要获得正确的行为,我们就无法忽略该检查点。

在您的情况下,它会对传入参数进行数据验证,尽管它并不能阻止客户端将来滥用该功能。特别是如果它们没有(也不应该)包含在发布版本中。

Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.

In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.

笑红尘 2024-09-12 04:24:59

它确保表达式返回 true。否则,它会抛出java.lang.AssertionError

http://java.sun.com/docs/ books/jls/third_edition/html/statements.html#14.10

It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError.

http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10

皇甫轩 2024-09-12 04:24:59

如果您在打开断言的情况下运行应用程序,Assert 确实会引发 AssertionError。

int a = 42;
assert a >= 0 && d <= 10;

如果您运行此命令,请说:java -ea -jar peiska.jar

它将抛出java.lang.AssertionError

Assert does throw an AssertionError if you run your app with assertions turned on.

int a = 42;
assert a >= 0 && d <= 10;

If you run this with, say: java -ea -jar peiska.jar

It shall throw an java.lang.AssertionError

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文