java的assert语句可以让你指定一条消息吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/273485/
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
Can java's assert statement allow you to specify a message?
提问by Allain Lalonde
Seems likes it might be useful to have the assert display a message when an assertion fails.
当断言失败时,让断言显示一条消息似乎很有用。
Currently an AssertionError
gets thrown, can you specify a custom message for it?
目前AssertionError
抛出了一个,你能为它指定一个自定义消息吗?
Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)?
你能展示一个这样做的示例机制吗(除了创建你自己的异常类型并抛出它)?
采纳答案by Greg Hewgill
You certainly can:
你当然可以:
assert x > 0 : "x must be greater than zero, but x = " + x;
See Programming with Assertionsfor more information.
有关更多信息,请参阅使用断言编程。
回答by Jason Coco
It absolutely does:
它绝对可以:
assert importantVar != null : "The important var was null!";
This will add "The important var was null" to the exception that is thrown.
这会将“重要的变量为空”添加到抛出的异常中。
回答by Bill the Lizard
If you use
如果你使用
assert Expression1 : Expression2 ;
Expression2 is used as a detail message for the AssertionError.
Expression2 用作 AssertionError 的详细消息。
回答by matt burns
assert (condition) : "some message";
I'd recommend putting the conditional in brackets
我建议将条件放在括号中
assert (y > x): "y is too small. y = " + y;
Imagine if you came across code like this...
想象一下,如果你遇到这样的代码......
assert isTrue() ? true : false : "some message";
Don't forget this has nothing to do with asserts you'd write in JUnit.
不要忘记这与您在 JUnit 中编写的断言无关。