Search code examples
javaapistringreader

Why Java StringReader throws IOException?


Today I was working with Java class StringReader and I found it very annoying that it throws IOException on read method. I know that it extends Reader class in which method read throw IOException but I think that it is not needed for StringReader. This class doesn't use any external resources that might cause errors.

After short investigation I found out that StringReader#read throws IOException if string which this class reads is null but de facto this can't happen because if we would try to pass null to StringReader constructor it throws NPE.

What do you think about it, is it good practice to always throw the same exceptions as super class?


Edit: As noted by U Mad Reader is a class not interface.


Solution

  • Please have a look at StringReader#read().

    Look at the source code of StringReader#read() method. It calls ensureOpen() method that is actually throwing IOException because ensureOpen() checks to make sure that the stream has not been closed.

    If reader is closed and then after read() is called again then what will happen?

    Source Code directly from above link (Look at the comments):

    /**
     * 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;
    }