java:Exception的另类用途-利用异常代替if判断的例子
2016-11-29 14:55
441 查看
有的时候,我们可以利用java的异常来代替一if判断,
以下面这代码片段为例,modifyFocus方法中为了防止List下标访问越界,用了if判断语句来判断下标是否有效。
我写代码有个习惯,就是if条件判断分支越少越好,能不用if判断的就尽量避免之,所以我利用java.lang.IndexOutOfBoundsException异常代替这个判断语句:
重写的modifyFocus方法如下,还省去临时变量focusIndex的定义:
以下面这代码片段为例,modifyFocus方法中为了防止List下标访问越界,用了if判断语句来判断下标是否有效。
public class AnnotationCanvas{ private List<AnnRectUI> rects; /** * 从rects中找到焦点对象(focus为true),没有找到则返回-1 */ private int getFocus(){ for(int i=0;i<rects.size();++i)if(rects.get(i).focus)return i; return -1; } /** * 修改焦点矩形 * @param rect */ public void modifyFocus(Rectangle rect){ int focusIndex = getFocus(); // 没找到焦点对象则返回 if(focusIndex <0)return; rects.get(focusIndex).setBounds(new AnnRectUI(rect.x,rect.y,rect.width,rect.height).unZoom(zoom)); drawAction=refreshAll; } }
我写代码有个习惯,就是if条件判断分支越少越好,能不用if判断的就尽量避免之,所以我利用java.lang.IndexOutOfBoundsException异常代替这个判断语句:
重写的modifyFocus方法如下,还省去临时变量focusIndex的定义:
/** * 修改焦点矩形 * @param rect */ public void modifyFocus(Rectangle rect){ try{ rects.get(getFocus()).setBounds(new AnnRectUI(rect.x,rect.y,rect.width,rect.height).unZoom(zoom)); drawAction=refreshAll; } catch (IndexOutOfBoundsException e) {} }
相关文章推荐
- 用if、Exception还是assert?——看JavaEye论坛帖子:《面试题:用Exception异常还是if判断》的感想
- JAVA打JAR包后,IF判断异常
- 用if、Exception还是assert?——看JavaEye论坛帖子:《面试题:用Exception异常还是if判断》的感想 .
- java异常处理和自定义异常利用try和catch让程序继续下去(回来自己再写个例子试运行下)
- java设计模——反射的应用 (利用反射来去除if判断语句)
- Junit测试一个spring静态工厂实例化bean的例子,出现java.lang.IllegalArgumentException异常。
- struts 2.3.15做例子时报异常:java.lang.RuntimeException: java.lang.reflect.InvocationTargetException 解决
- java 利用Java if和switch语句实现判断闰年
- 用if、Exception还是assert—看JavaEye帖子:面试题:用Exception异常还是if判断》的感想 推荐
- struts 2.2.1做例子时报异常:java.lang.RuntimeException: java.lang.reflect.InvocationTargetException 解决
- 关于程序Exception抛出异常和利用返回值去做判断的思考
- 用if、Exception还是assert—看JavaEye帖子:面试题:用Exception异常还是if判断》的感想
- Java异常(Exception)小例子&知识点【Java学习笔记】
- 利用 操作符特性 代替if判断语句
- java 中利用UncaughtExceptionHandler捕获异常
- struts 2.2.1做例子时报异常:java.lang.RuntimeException: java.lang.reflect.InvocationTargetException 解决
- [Java经典题目]利用if语句判断分数等级
- Java中利用设计模式来代替复杂的if...else...语句(三层以上的嵌套循环)
- 什么是异常,我们为什么要关心它--The Java Tutorial--Exception第一节
- java.util.ConcurrentModificationException 异常