java - 该文档背后的意图是什么?

标签 java string exception throw

在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 异常(即子类型)。示例 - ArrayIndexOutOfBoundsStringIndexOutOfBounds。它们都是运行时异常(IndexOutOfBoundsException 扩展了RuntimeException)。它们只是通过调用 super() 来遵循标准异常委托(delegate)模型,因为异常类型是相同的 (IndexOutOfBounds)。因此设计。

它们让父级通过传递自定义消息(优雅地)处理异常。

关于java - 该文档背后的意图是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26464401/

相关文章:

java - 迭代器是如何在 Java 中实现的?

c# - 使用 "Convert.ChangeType()"将 System.String 一般转换为任何复杂类型

java - 在 Apache Netbeans9 中创建新 Maven 项目时出现异常

java - 详细的异常捕获子句

java - 一本 Java 书就够了吗,还是我必须先学习算法?

java - 替换字符串中所有其他两个Java字符之间的字符

java - 硬编码区域、城市、国家字符串

java - 如何从多个字符串中解析文本?

java - 空结果与为可预测但无法预防的故障抛出异常

java - Jetty servlet 未检测到客户端已断开连接