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)