// Java 断言示例代码
public class AssertExample {
// 使用断言检查参数是否为正数
public static void checkPositive(int number) {
// 断言:如果 number <= 0,则抛出 AssertionError 异常
assert number > 0 : "number should be positive";
System.out.println("The number is positive: " + number);
}
public static void main(String[] args) {
// 启用断言的方式运行程序:java -ea AssertExample
// 如果不启用断言(即不加 -ea 参数),断言将被忽略
// 测试正常情况
checkPositive(10); // 输出: The number is positive: 10
// 测试异常情况(当启用断言时会抛出 AssertionError)
checkPositive(-5); // 抛出 AssertionError: number should be positive
}
}
assert
关键字用于定义断言。其语法为 assert condition : message;
,其中 condition
是一个布尔表达式,message
是可选的错误信息。checkPositive
方法使用断言来确保传入的参数 number
是正数。如果 number
不是正数且启用了断言,则会抛出 AssertionError
并附带错误信息。-ea
参数,例如:java -ea AssertExample
。上一篇:java比较字符串大小的方法
下一篇:javaweb开发
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站