版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/88915758
Java assertion statements come in two forms:
assert boolean-expression;
assert boolean-expression: information-expression;
For example:
case 1,
// validating/Assert1.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Non-informative style of assert
// Must run using -ea flag:
// {java -ea Assert1}
// {ThrowsException}
public class Assert1 {
public static void main(String[] args) {
assert false; // false produce error
}
}
/* My Output:
Exception in thread "main" java.lang.AssertionError // since 1.4, parent class is Error
at Assert1.main(Assert1.java:12)
*/
execute the above code
./gradlew validating:Assert1
or cd validating directory, run
$ javac Assert1.java
# -ea means -enableassertions
$ java -ea Assert1
case 2,
// validating/Assert2.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Assert with an information-expression
// {java Assert2 -ea}
// {ThrowsException}
public class Assert2 {
public static void main(String[] args) {
assert false : "Here's a message saying what happened";
}
}
/* My Output:
Exception in thread "main" java.lang.AssertionError:
Here's a message saying what happened
at Assert2.main(Assert2.java:11)
*/
references:
1. On Java 8 - Bruce Eckel
扫描二维码关注公众号,回复:
5886398 查看本文章
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/validating/Assert1.java
3. https://docs.oracle.com/javase/8/docs/api/java/lang/AssertionError.html
5. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/validating/Assert2.java