您的位置:首页 > 编程语言 > Java开发

java:Exception的另类用途-利用异常代替if判断的例子

2016-11-29 14:55 441 查看
有的时候,我们可以利用java的异常来代替一if判断,

以下面这代码片段为例,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) {}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java exception if
相关文章推荐