天天看點

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");
    }