assert 介绍

assert 关键字需要在运行时候显式开启才能生效,否则你的断言就没有任何意义,assert 断言失败将面临程序的退出。

assert 用法

1、assert <boolean表达式>

2、assert <boolean表达式> : <错误信息表达式>

代码测试

public class Test {
    //判断成绩是否合格
    public boolean assertScore(int score) {
        if(score >= 90) {
            return true;
        }
        return false;
    }
	
    public static void main(String[] args) {
	    Test t = new Test();
        assert t.assertScore(95): "断言失败,95分没有及格了呀!";
        assert t.assertScore(85): "断言失败,85分没有及格了呀!";  
    }
}

结果:
Exception in thread "main" java.lang.AssertionError: 断言失败,85分没有及格了呀!

相关文章:

  • 2021-12-27
  • 2022-12-23
  • 2022-01-21
  • 2022-03-04
  • 2022-01-30
  • 2022-12-23
猜你喜欢
  • 2021-12-16
  • 2022-01-20
  • 2021-04-26
  • 2021-09-03
  • 2021-12-05
相关资源
相似解决方案