3.8 Handling Errors using IIOException

In the examples above, the possibility of fatal errors was not considered. Errors may result from a number of sources, including true I/O errors (e.g., file not found, file unreadable, file on corrupt media), security violations (e.g., no permission to read files from an applet), file format problems (file contents corrupted, file using a variant of the format that is not supported by the plug-in), or even bugs in the API implementation or in the plug-in.

The Image I/O API makes use of its own subclass of the standard IOException class, called IIOException. IIOExceptions are used to signal all errors encountered during the parsing of a source file (e.g., an incorrect checksum or an invalid value for a particular byte within the file), including true I/O errors that result in an IOException being thrown within the reader.

An IIOException contains a (non-localized) message describing the reason for the exception, as well as a reference to another Exception that was the cause of the IIOException, if one exists.

Thus, application code that attempts to provide graceful handling of errors will look something like:

File f = new File("c:\images\myimage.gif");
ImageInputStream iis = null;
try {
        iis = ImageIO.createImageInputStream(f);
} catch (IIOException iioe1) {
        System.out.println("Unable to create an input stream!");

try {, param);
} catch (IIOException iioe2) {
        System.out.println("An error occurred during reading: " +
        Throwable t = iioe2.getCause();
        if ((t != null) && (t instanceof IOException)) {
                System.out.println("Caused by IOException: " +


Copyright © 1993, 2017, Oracle and/or its affiliates. All rights reserved.