OCJP之assert

OCJP: assert


新手边学边整理,错误之处,请指正,谢谢!


语法:

assert <boolean表达式>


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

当boolean表达式为false时,抛出AssertError,程序终止运行。


不适用assert的情况:

1)不能用于验证public方法的参数

因为公有方法的参数,如果为非法,应该抛异常(比如IndexOutOfBoundsException),加了assert后,屏蔽了异常。。。不方便排错

2)不能将业务逻辑写在assert后面

因为assert是否开启,取决于运行时,是否enableassertions,如果没有开启assert,后面的逻辑得不到抛行。

正确的做法,是先处理逻辑,然后调用assert

比如:

boolean removeNull = names.remove(null);

assert removeNull;


assert的作用域

1)类级 -ea/-da,如果后面指定参数,是针对当前类,不指定参数,开启所有的类的assert.

2) 包级 -ea/-da,不包括系统级的包

3) 系统级 -esa/-dssa


运行时开启或者禁用assert:

java –ea TestAssert //打开断言,只对一个类

 java -ea:com.wombat.fruitbat... BatTutor //打开断言,对包,com.wombat.fruitbatand its subpackages

 

参数还可以为:

-da //disableassertions

-esa //enable systemassertions

-dsa //disable systemassertions

-enableassertions

-disableassertions

-enablesystemassertions

-disablesystemassertions


一道题目的分析:


package com.ocjp.testAssert;

public class Cloned {
    public static void main(String[] args) {
        System.out.println("classes");
        try{
            //when running as java -ea Cloned -5, it's supposed to throw AssertError;
            assert (Integer.parseInt(args[0]) > 0):"assertTest";
        }catch(Exception e){
            //Exception fails to catch "AssertError"; so no chance to execute the following block;
            System.out.println("catch exec..");
        }
        //finally will be always executed before main() is done.
        //Once any exception is thrown out here, program terminates here...Hence no chance to throw assertError;
        finally{
            throw new IllegalArgumentException();
        }
    }
}


//Output when running java -ea Cloned -5

classes
Exception in thread "main" java.lang.IllegalArgumentException
    at com.ocjp.testAssert.Cloned.main(Cloned.java:12)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值