2014-10-20 43 views
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?

+0

後者是前者的子類,所以文檔和代碼都是正確的。根據javadocs的說法,從JDK 1.0開始就是這樣。 – duffymo 2014-10-20 11:20:41

+1

它符合Liskov的替代原則(http://en.wikipedia.org/wiki/Liskov_substitution_principle) – 2014-10-20 11:24:32

回答

1

請參閱,有多個例外(即,子類型)IndexOutOfBounds。示例 - ArrayIndexOutOfBounds,StringIndexOutOfBounds。他們都是運行時異常IndexOutOfBoundsException延伸RuntimeException)。他們只是通過調用super()來遵循標準異常委託模式,因爲異常類型相同(IndexOutOfBounds)。因此設計。

他們讓父母通過傳遞自定義消息來處理異常(優雅地)。

相關問題