语法:assert <boolean表达式> assert <boolean表达式> : <错误信息表达式> 当boolean表达式为false时,抛出AssertError,程序终止运行。例子: 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(); } } }
这个cookie就只有两个元素,
我断言一下,如果取到的对应的cookie里的对象的元素不是两个,
那么直接抛异常,或者不往下处理了。
aseert应该是个操作符,和instanceof差不多,aseert接受一个运算结果是boolean的表达式
据说是在JDK1.4以后才有的,所以编译时需要加 -source 1.4 来指定版本,本人zaieclipse中试的时候,使用的默认编译方式,可以生效,可能eclipse已经设定过。
重点是运行时需要设置虚拟机参数 -ea 打开断言开关才能在运行时生效,否则虚拟机忽略断言语句可以在main方法中加assert false;
断言开关打开的话,会出现Exception in thread "main" java.lang.AssertionError,
没有打开就不报错。
assert <boolean表达式> : <错误信息表达式>
当boolean表达式为false时,抛出AssertError,程序终止运行。例子:
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();
}
}
}
如
int i=0;
...
具体其他代码
....
try{
assert i>10 ; //认为在这里 i肯定必须大于10
}
catch(Exception e){}
如何使程序中定义的断言起作用
在命令行执行的时候 加上 java -ea 参数 此时 如果发现断言错误 会发生ERROR 程序停止具体可以参考楼上的代码 写的非常好