062_Assert

assert关键字用法简单,但是使用assert往往会让你陷入越来越深的陷阱中。应避免使用。总结了以下原因:
 
1、用assert代替if是陷阱之二。assert的判断和if语句差不多,但两者的作用有着本质的区别:assert关键字本意上是为测试 调试程序时使用的,但如果不小心用assert来控制了程序的业务流程,那在测试调试结束后去掉assert关键字就意味着修改了程序的正常的逻辑。
 
2、assert断言失败将面临程序的退出。这在一个生产环境下的应用是绝不能容忍的。一般都是通过异常处理来解决程序中潜在的错误。但是使用断言就很危险,一旦失败系统就挂了。
 
如果<boolean表达式>为true,则程序继续执行。
如果为false,则程序抛出AssertionError,并终止执行。
 
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry'); // Insert a new key-value pair in the map
m.put(2, 'Second entry'); // Insert a new key-value pair in the map
System.assert(m.containsKey(3)); // Assert that the map contains a key
String value = m.get(2); // Retrieve a value, given a particular key
System.assertEquals('Second entry1', value);
Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map

 System.assert(m.containsKey(3));


==>System.AssertException: Assertion Failed 因为3 不在key范围内,因此出错,即程序中断

 

 

猜你喜欢

转载自www.cnblogs.com/bandariFang/p/9662011.html
062
今日推荐