在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 的目的是什么?
最佳答案
看,有多个 IndexOutOfBounds
异常(即子类型)。示例 - ArrayIndexOutOfBounds
、StringIndexOutOfBounds
。它们都是运行时异常(IndexOutOfBoundsException
扩展了RuntimeException
)。它们只是通过调用 super()
来遵循标准异常委托(delegate)模型,因为异常类型是相同的 (IndexOutOfBounds
)。因此设计。
它们让父级通过传递自定义消息(优雅地)处理异常。
关于java - 该文档背后的意图是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26464401/