Handling IO exceptions in Java

fredoverflow picture fredoverflow · Jun 6, 2011 · Viewed 17.3k times · Source

Basically, I want to open a file, read some bytes, and then close the file. This is what I came up with:

try
{
    InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
    try
    {
        // ...
        inputStream.read(buffer);
        // ...
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        try
        {
            inputStream.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
catch (FileNotFoundException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Maybe I'm spoiled by RAII, but there must be a better way to do this in Java, right?

Answer

vitaut picture vitaut · Jun 6, 2011

If you have the same exception handling code for IOException and FileNotFoundException then you can rewrite your example in a more compact way with only one catch clause:

try {
    InputStream input = new BufferedInputStream(new FileInputStream(file));
    try {
        // ...
        input.read(buffer);
        // ...
    }
    finally {
        input.close();
    }
}
catch (IOException e) {
    e.printStackTrace();
}

You can even get rid of the outer try-catch if you can propagate the exception which probably makes more sense then manually printing the stack trace. If you don't catch some exception in your program you'll get stack trace printed for you automatically.

Also the need to manually close the stream will be addressed in Java 7 with automatic resource management.

With automatic resource management and exception propagation the code reduces to the following:

try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
    // ...
    input.read(buffer);
    // ...
}