Search code examples
javastringexceptionthrow

What's the intent behind this documentation?


In Java class String method charAt() there is an exception thrown at one case. The exception thrown is specified in documentation to be IndexOutOfBoundsException. The actual exception that is thrown is StringIndexOutOfBoundsException - a subclass of 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];
}

What is the intent to write in documentation IndexOutOfBoundsException instead of StringIndexOutOfBoundsException ?


Solution

  • See, there are multiple IndexOutOfBounds exceptions (i.e, subtypes). Example - ArrayIndexOutOfBounds, StringIndexOutOfBounds. They are all Runtime Exceptions (IndexOutOfBoundsException extends RuntimeException). They just follow the standard exception delegation model by calling super() because the Exception type is the same (IndexOutOfBounds). Hence the design.

    They let the parent handle the Exception (gracefully) by passing custom messages.