31

I have never seen a case when an IOError is thrown. The only thing that the docs say about IOError it this:

Thrown when a serious I/O error has occurred.

There aren't any subclasses or anything else obvious.

Is there ever a case when IOError would be thrown in java? What might cause it?

(This is not to be confused with IOException -- IOException is thrown in a wide range of cases, and is commonly used; I know that. I'm wondering about the less common IOError).

Will Richardson
  • 7,780
  • 7
  • 42
  • 56
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
  • 2
    @Harvtronix The question is about `IOError`, not `IOException`. – takendarkk Mar 23 '15 at 02:57
  • @Harvtronix Yes, I linked to IOException initially. But I'm referring to IOError. Seems like people are mixing the two up? I may need to edit this for clarity (EDIT: I have made an edit addressing that) – Pokechu22 Mar 23 '15 at 02:58
  • Whoops! My bad. Sorry! – Harvtronix Mar 23 '15 at 02:58
  • 1
    The question is clear enough to me, but all three answers (one deleted) that have been posted seem to have misunderstood. – Wyzard Mar 23 '15 at 03:02

8 Answers8

18

Console, Path#toAbsolutePath, and Path#toUri declare this particular exception to be thrown. Of course, that's a documentation fact and not an actual declaration; since Error is a runtime exception, declaring it to be thrown in the signature would have no meaning.

From what it looks like in code, Console#readLine and Console#readPassword catch an IOException that results through its normal operation, then propagate that to an IOError.

Essentially, IOError represents a critical failing of the underlying filesystem, or accessing some resource that ties Java to the file system. It's not thrown often, but it has the potential to be thrown if something serious happens from within the file system.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 4
    You can check the [list of usages in the code](http://grepcode.com/search/usages?id=repository.grepcode.com$java$root@jdk$openjdk@7u40-b43@java$io@IOError&start=0&type=type&k=u). Inside the JDK I can only find `Console`, `sun.nio.fs.WindowsPath`, and `sun.nio.fs.WindowsLinkSupport`. – Philipp Wendler Mar 27 '15 at 19:45
  • @PhilippWendler: I'm on a Linux box so those wouldn't be thrown for me. I was more or less covering the general cases under when it'd be raised. – Makoto Mar 27 '15 at 19:46
  • 1
    "since Error is a runtime exception" - This is an incorrect statemen. `RuntimeException` is a subtype of `Exception`. `Error` is another category of `Throwable`. – hfontanez Oct 30 '20 at 18:44
  • @hfontanez - I *did* say it was a "runtime exception" as in an exception that can manifest during runtime, not that it was a subclass of `RuntimeException` which is very different indeed. Both exceptions are raised during runtime. Only `RuntimeException`s or its children make any amount of sense to catch or handle by an application. – Makoto Oct 31 '20 at 00:28
  • Also @hfontanez only `Exception`s need to be declared to be thrown. So, everything else doesn't need to be declared. That is, every actual runtime exception doesn't need to be declared thrown since there's no feasible way to deal with an `IOError` during the run of an application. – Makoto Oct 31 '20 at 00:30
  • @Makoto you wrote [I did say it was a "runtime exception"]. Again, that statement is incorrect. Read the Java documentation on Exceptions. `Error` and `Exceptions` ARE NOT the same thing and are not to be handled in the same manner. These are not my words. These are the words of the architects of the Java language. Read my posted answer. – hfontanez Nov 03 '20 at 15:45
6

Is there ever a case when IOError would be thrown in java?

import java.io.IOError;

public class Test {

    public static void main(String[] args) {
        throw new IOError(new Exception());
    }

}

will result in

Exception in thread "main" java.io.IOError: java.lang.Exception
    at test.Test.main(Test.java:13)
Caused by: java.lang.Exception
    ... 1 more
Java Result: 1

I believe you expect a case which is more likely to happen.

An IOError would be thrown for example when trying to read from a console where the input stream has been closed.

You can try to run this snippet

import java.io.*;

public class Test {

    public static void main(String[] s) {
        Console con = System.console();
        try {
            InputStreamReader reader = new InputStreamReader(System.in);
            reader.close();
            String st = con.readLine("%s", "Enter a line");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IOError error) {
            error.printStackTrace();
        }
    }
}

That would result in

java.io.IOError: java.io.IOException: Stream Closed
    at java.io.Console.readLine(Console.java:254)
    at Test.main(Test.java:10)
Caused by: java.io.IOException: Stream Closed
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:246)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.Console$LineReader.read(Console.java:437)
    at java.io.Console.readline(Console.java:376)
    at java.io.Console.readLine(Console.java:250)
    ... 1 more
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
6

Here is an explanation from Mark Reinhold from Oracle:

The new IOError class was defined in combination with the new java.io.Console class. It’s for use in situations where an unrecoverable I/O error occurs and the most appropriate response is to terminate the program rather than attempt to handle the exception.

The IOError class, along with many other enhancements, will be documented in the forthcoming Mustang maintenance review in the JCP.

http://cafe.elharo.com/blogroll/undocumented-changes-in-java-6-mustang-ioerror/

RRM
  • 2,495
  • 29
  • 46
4

IOError is seldomly used. I think its major usecase is in java.io.Console#readLine() and readPassword(), which by default do not throw IOExeption (but wrap it) in order to signal I/O problems.

My guess the motivation for this is, that it is so seldom they did not want to declare a checked exception. It can happen when the terminals have problems - and this is nowadays where you don't have serial lines anymore only happening on severe system conditions like running out of memory or handles.

eckes
  • 10,103
  • 1
  • 59
  • 71
4

One official source to look for is the Java Bug Database where you can search for bugs involving IOError by using the search keyword. This can show some real cases involving this error.

One occurrence that directly references this error (at least that's what I've been able to find) was in JDK-6347312 which deals with Console.readLine().

There are also few usages in the JDK. Most probably it is used to a signal a "critical" IOException-like exception that the caller is not supposed to handle (as is the case with other runtime exceptions).

M A
  • 71,713
  • 13
  • 134
  • 174
  • 1
    A strange answer. What if there weren't any bugs related to IOError? Does that really prove it is never used? – user207421 Mar 29 '15 at 18:55
  • 2
    @EJP My intention is to show real examples of situations where an `IOError` has occurred, not really about bugs about it. I have removed the part that concludes about it being rarely used though. – M A Mar 29 '15 at 19:28
3

IOError being a runtime exception and being classified under Error category it is an unchecked exception. To me this seems to occur when you interact with the system using JNI/native calls by the JVM to the underlying OS system calls. This might be to gain access to the IO devices( Storage,keyboard,display,network etc.) . But i have hardly seen it being used in the Java API docs.Most probably the reason being that the implementers wanted to keep the dependency on the underlying system to the minimal.

Rohitdev
  • 866
  • 6
  • 15
2

Just to add to this, RedHat JBoss Wildfly domain management library explicitly throws IOError for their ConsoleWrapper interface. The only implementation I've seen, so far of the interface is JavaConsole class.

Source:

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2012, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.as.domain.management.security.adduser;

import java.io.IOError;
import java.util.IllegalFormatException;

/**
 * Wrap the console commands
 *
 * @author <a href="mailto:flemming.harms@gmail.com">Flemming Harms</a>
 */
public interface ConsoleWrapper<T> {

    /**
     * Writes a formatted string to this console's output stream using
     * the specified format string and arguments.
     * see <a href="../util/Formatter.html#syntax">Format string syntax</a>
     * @param fmt
     * @param args
     */
    T format(String fmt, Object ...args) throws IllegalFormatException;

    /**
     * A convenience method to write a formatted string to this console's
     * output stream using the specified format string and arguments.
     *
     * @param format
     * @param args
     * @throws IllegalStateException
     */
    void printf(String format, Object ... args) throws IllegalFormatException;

    /**
     * Provides a formatted prompt, then reads a single line of text from the
     * console.
     *
     * @param fmt
     * @param args
     * @return A string containing the line read from the console, not
     *          including any line-termination characters, or <tt>null</tt>
     *          if an end of stream has been reached.
     * @throws IOError
     */
    String readLine(String fmt, Object ... args) throws IOError;

    /**
     * Provides a formatted prompt, then reads a password or passphrase from
     * the console with echoing disabled.
     *
     * @param fmt
     * @param args
     * @return  A character array containing the password or passphrase read
     *          from the console.
     * @throws IOError
     */
    char[] readPassword(String fmt, Object ... args) throws IllegalFormatException, IOError;

    /**
     *  Return the console object
     *
     * @return Return the console object
     */
    T getConsole();
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
-1

I am not sure why so many people state that errors are Runtime Exceptions. They are not. Simply look at the API. Error is a different Throwable category than Exception. RuntimeException is a subtype of Exception.

In simple terms, Error (and its subtypes) are used to indicate serious problems that a reasonable application should not try to catch. On the other hand Exception are used to indicate conditions that a reasonable application MIGHT want to catch. It doesn't say that you MUST. The reason it states MIGHT is because RuntimeException is a subtype of Exception and any condition that result on a runtime exception should be fixed (most likely) during development time so that when the application is deployed, there should not be any need to handle those types of conditions. However, the option is open to continue to use a catch clause for them.

Bottom line: Error IS NOT a RuntimeException. To state this is simply wrong.

hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • True, it looks like Java calls subclasses of `Error` and `RuntimeException` "unchecked exceptions": https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Error.html, https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/RuntimeException.html. However, this should be a comment on the answers, not an answer itself. – Solomon Ucko Jul 06 '22 at 23:58
  • @SolomonUcko and neither is the one that was awarded 50 bounty points and has been upvoted 5 times. – hfontanez Jul 07 '22 at 06:47