0
点赞
收藏
分享

微信扫一扫

java异常中if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index));


public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
}

private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}

private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

上述源码出自LinkedList.class.
对于if语句后直接抛出异常看上去还是一脸懵的.

这样写就是可以直接抛出异常信息,根据自己定义的情况来抛出从而终止后面程序的运行.

测试代码:

List list = new LinkedList();
list.add(2);
list.add(12);
System.out.println(list.size());
if (list.size() < 0) {
throw new IndexOutOfBoundsException("size()<0");
} else {
throw new IndexOutOfBoundsException("size()>0");
}

结果:
​​​1​​​​2​​​​Exception in thread "main" java.lang.IndexOutOfBoundsException: size()>0 at cn.com.clearlight.test.CollectionsDemo.main(CollectionsDemo.java:28)​​ 如果再往下面if-else语句后面写代码的话将出现错误信息:Unreachable code

这样就容易理解源码中的这种写法了.


举报

相关推荐

0 条评论