Java “assert”关键字有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3018683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the "assert" keyword do?
提问by Peiska
What does assert
do?
For example in the function:
有什么作用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);
}
采纳答案by aioobe
If you launch your program with -enableassertions
(or -ea
for short) then this statement
如果您使用-enableassertions
(或-ea
简称)启动程序,则此语句
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.
如果您在没有此选项的情况下启动程序,则 assert 语句将无效。
For example, assert d >= 0 && d <= s.length();
, as posted in your question, is equivalent to
例如,assert d >= 0 && d <= s.length();
正如您在问题中发布的那样,相当于
if (!(d >= 0 && d <= s.length()))
throw new AssertionError();
(If you launched with -enableassertions
that is.)
(如果你是这样启动的-enableassertions
。)
Formally, the Java Language Specification: 14.10. The assert
Statementsays the following:
正式的Java 语言规范:14.10。该assert
声明说,以下情况:
14.10. The
assert
Statement
An assertion is anassert
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 reportedif the expression evaluates tofalse
. If the assertion is disabled, execution of the assertion has no effect whatsoever.
14.10. 的
assert
声明
的断言是一个assert
含有一个布尔表达式语句。断言被启用或禁用。如果启用了断言,则断言的执行会导致对布尔表达式进行评估,如果表达式的计算结果为 ,则会报告错误false
。如果断言被禁用,则断言的执行没有任何影响。
Where "enabled or disabled"is controlled with the -ea
switch and "An error is reported"means that an AssertionError
is thrown.
其中“启用或禁用”由-ea
开关控制,“报告错误”意味着AssertionError
抛出一个。
And finally, a lesser known feature of assert
:
最后,一个鲜为人知的特性assert
:
You can append : "Error message"
like this:
您可以: "Error message"
像这样附加:
assert d != null : "d is null";
to specify what the error message of the thrown AssertionError should be.
指定抛出的 AssertionError 的错误消息应该是什么。
This post has been rewritten as an article here.
这篇文章在这里被改写为一篇文章。
回答by Brett Kail
It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError
.
它确保表达式返回 true。否则,它会抛出一个java.lang.AssertionError
.
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10
回答by Chris Thompson
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
assert
是一个调试工具,AssertionFailed
如果条件不成立,它会导致程序抛出异常。在这种情况下,如果其后的两个条件中的任何一个评估为 false,则程序将抛出异常。 一般来说,assert
不应在生产代码中使用
回答by Jan Kuboschek
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.
使用此版本的 assert 语句为 AssertionError 提供详细消息。系统将 Expression2 的值传递给适当的 AssertionError 构造函数,该构造函数使用该值的字符串表示作为错误的详细消息。
详细消息的目的是捕获和传达断言失败的详细信息。该消息应允许您诊断并最终修复导致断言失败的错误。请注意,详细消息不是用户级别的错误消息,因此通常没有必要使这些消息孤立地易于理解,或者将它们国际化。详细消息旨在在完整堆栈跟踪的上下文中解释,并结合包含失败断言的源代码。
回答by Richard Fearn
If the condition isn't satisfied, an AssertionError
will be thrown.
如果条件不满足,AssertionError
将抛出一个。
Assertions have to be enabled, though; otherwise the assert
expression does nothing. See:
但是,必须启用断言;否则assert
表达式什么都不做。看:
http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable
http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable
回答by NoozNooz42
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
如果你运行它,说:java -ea -jar peiska.jar
It shall throw an java.lang.AssertionError
它会抛出一个java.lang.AssertionError
回答by Zoli
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.
在您的情况下,它对传入参数进行数据验证,但它不会阻止客户端将来滥用该函数。特别是如果它们不是,(也不应该)包含在发布版本中。
回答by felixwcf
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
您可能会收到警告(在 strB = strA.toLowerCase(); 上显示黄线)strA 可能会为 strB 生成 NULL 值。虽然你知道 strB 最终绝对不会为空,但为了以防万一,你使用 assert 来
1. Disable the warning.
1. 禁用警告。
2. Throw Exception error IF worst thing happens (when you run your application).
2. 抛出异常错误如果最坏的事情发生(当你运行你的应用程序时)。
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.
您告诉编译器 strA 绝对不是空值,它可以“和平地”关闭警告。如果它是 NULL(最坏的情况发生),它将停止应用程序并向您抛出一个错误来定位它。