zoukankan      html  css  js  c++  java
  • Java中assert(断言)的使用

    2018年08月31日 21:51:07 jeikerxiao 

    1.IDEA打开断言

    1.IDEA中默认assert(断言)是关闭,开启方式如下:

    简单来说:就是设置一下jvm的参数,参数是-enableassertions或者-ea(推荐)。

    这里写图片描述

    2.assert格式

    1.格式1

    assert [boolean 表达式]
    • 如果[boolean表达式]为true,则程序继续执行。
    • 如果为false,则程序抛出AssertionError,并终止执行。

    示例

    public class Test1 {
    
        public static void main(String[] args) {
            int a = 1;
            int b = 2;
            // 格式1:assert [boolean 表达式]
            assert a > b;
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    增加 jvm 参数 -ea,运行,输出日志如下:

    Exception in thread "main" java.lang.AssertionError
        at Test1.main(Test1.java:12)
    
    Process finished with exit code 1
    • 1
    • 2
    • 3
    • 4

    2.格式2

    assert [boolean 表达式 : 错误表达式 (日志)]
    • 1
    • 如果[boolean表达式]为true,则程序继续执行。
    • 如果为false,则程序抛出java.lang.AssertionError,输出[错误信息]。

    示例

    public class Test2 {
    
        public static void main(String[] args) {
            int a = 1;
            int b = 2;
            // 格式2:assert [boolean 表达式] : [错误表达式 (日志)]
            assert a > b : "错误,a不大于b";
        }
    }

    增加 jvm 参数 -ea,运行,输出日志如下:

    Exception in thread "main" java.lang.AssertionError: 错误,a不大于b
        at Test2.main(Test2.java:12)
    
    Process finished with exit code 1

    备注:assert boolean表达式如果是false会造成如下问题:

  • 相关阅读:
    KVM -> 热迁移_05
    KVM -> 虚拟机磁盘管理_03
    使用光盘搭建本地yum源
    KVM -> 虚拟机管理&console登录_02
    使用windows-SQLyog连接linux-mysql
    linux下登陆mysql失败
    忘记root密码时如何重设密码
    批处理程序:自动登陆服务端,并循环执行某些命令
    linux--磁盘分区
    linux--档案与目录管理
  • 原文地址:https://www.cnblogs.com/grj001/p/12225575.html
Copyright © 2011-2022 走看看