这份文件背后的意图是什么?

问题描述 投票:0回答:1

在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中写入的意图是什么?

java string exception throw
1个回答
1
投票

看,有多个IndexOutOfBounds例外(即子类型)。示例 - ArrayIndexOutOfBoundsStringIndexOutOfBounds。它们都是运行时异常(IndexOutOfBoundsException扩展RuntimeException)。他们只是通过调用super()来遵循标准的异常委托模型,因为Exception类型是相同的(IndexOutOfBounds)。因此设计。

他们让父母通过传递自定义消息来处理Exception(优雅地)。

© www.soinside.com 2019 - 2024. All rights reserved.