今天,我正在使用Java类StringReader,但发现它在read方法上引发IOException非常令人讨厌。我知道它扩展了Reader类,其中read方法引发IOException,但我认为StringReader不需要它。此类不使用任何可能导致错误的外部资源。

经过简短的调查,我发现如果此类读取的字符串为null,则StringReader#read会引发IOException,但事实上,此不会发生,因为如果我们尝试将null传递给StringReader构造函数,则会引发NPE。

您如何看待,是否总是抛出与父类(super class)相同的异常是一种好习惯?

编辑:
正如U Mad Reader所指出的那样,类不是接口(interface)。

最佳答案

请看看StringReader#read()

查看StringReader#read()方法的源代码。它调用实​​际上会引发ensureOpen()IOException方法,因为ensureOpen()检查以确保未关闭流。

如果读者关闭,然后再次调用read()后,会发生什么?

源代码直接来自上面的链接(请看注释):

/**
 * Reads a single character.
 *
 * @return     The character read, or -1 if the end of the stream has been
 *             reached
 *
 * @exception  IOException  If an I/O error occurs
 */
public int read() throws IOException {
    synchronized (lock) {
        ensureOpen();
        if (next >= length)
            return -1;
        return str.charAt(next++);
    }
}

/** Check to make sure that the stream has not been closed */
private void ensureOpen() throws IOException {
    if (str == null)
        throw new IOException("Stream closed");
}

/**
 * Closes the stream and releases any system resources associated with
 * it. Once the stream has been closed, further read(),
 * ready(), mark(), or reset() invocations will throw an IOException.
 * Closing a previously closed stream has no effect.
 */
public void close() {
    str = null;
}

关于java - 为什么Java StringReader抛出IOException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23127020/

10-11 05:05