在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 :(得分:1)
请参阅,有多个IndexOutOfBounds
例外(即子类型)。示例 - ArrayIndexOutOfBounds
,StringIndexOutOfBounds
。它们都是运行时异常(IndexOutOfBoundsException
extends RuntimeException
)。它们只是通过调用super()
来遵循标准异常委派模型,因为异常类型是相同的(IndexOutOfBounds
)。因此设计。
他们让父母通过传递自定义消息来处理Exception(优雅地)。