validating - Java Assertion Syntax

本文介绍了Java中的断言机制,展示了两种不同形式的断言语句,并通过两个具体示例解释了如何使用这些断言来验证条件是否为真。此外,还说明了运行包含断言的程序时需要启用断言功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

4. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/AssertionError.java

5. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/validating/Assert2.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值