0
在Java類String method charAt()中,在一種情況下會引發異常。拋出的異常在文檔中指定爲IndexOutOfBoundsException。拋出的實際異常是StringIndexOutOfBoundsException - IndexOutOfBoundsException的子類。本文檔背後的意圖是什麼?
/**
* Returns the <code>char</code> value at the
* specified index. An index ranges from <code>0</code> to
* <code>length() - 1</code>. The first <code>char</code> value of the sequence
* is at index <code>0</code>, the next at index <code>1</code>,
* and so on, as for array indexing.
*
* <p>If the <code>char</code> value specified by the index is a
* <a href="Character.html#unicode">surrogate</a>, the surrogate
* value is returned.
*
* @param index the index of the <code>char</code> value.
* @return the <code>char</code> value at the specified index of this string.
* The first <code>char</code> value is at index <code>0</code>.
* @exception IndexOutOfBoundsException if the <code>index</code>
* argument is negative or not less than the length of this
* string.
*/
public char charAt(int index) {
if ((index < 0) || (index >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index + offset];
}
在文檔中寫什麼意圖寫入IndexOutOfBoundsException而不是StringIndexOutOfBoundsException?
後者是前者的子類,所以文檔和代碼都是正確的。根據javadocs的說法,從JDK 1.0開始就是這樣。 – duffymo 2014-10-20 11:20:41
它符合Liskov的替代原則(http://en.wikipedia.org/wiki/Liskov_substitution_principle) – 2014-10-20 11:24:32