I very much prefer this approach:

OutputStream out = new MyOutputStream(...); //may throw IOException
try {
    //use the stream
} finally {
    out.close();
}

than this:

OutputStream out = null;
try {
    out = new MyOutputStream(...); //may throw IOException
    //use the stream
} finally {
    if (out != null) {
        out.close();
    }
}

I just find the first example correct and the second incorrect. I see the second ‘pattern’ everywhere.

Opinions?


4 Responses to “I/O Exception handling”  

  1. 1 tbee

    You’d have to have a second try-catch to deal with the IOException. I’ve improved the second pattern with a custom close method:

    OutputStream out = null;
    try {
    out = new MyOutputStream(…); //may throw IOException
    //use the stream
    }
    finally {
    out = IOUtil.close(out);
    }

    The close only closes if the parameter null and always returns null.
    BTW, the new Java 7 pattern is

    try (
    OutputStream out = new MyOutputStream(…); //may throw IOException
    )
    {
    //use the stream
    }
    finally {
    // auto closes
    }

  2. 2 Luigi

    tbee, not true, I’d tipically let the IOException flow out of the method, since IOException most of the time can’t be recovered (i.e. just report the failure to the user with a proper message).

    Before using try/catch[/finally], I’d think if I can actually do something to handle the exception when it is raised. I write much more often try/finally than try/catch[/finally].

  3. 3 blink4blog

    I agree with the first method base on the assumptions of the following:

    1. The exception is not recovrable
    2. The exception is not expected to the catchable
    3. There is no business value to catch the exception unless the logic can proceed without the IOStream presence.
    4. The exception give technical information for system administrator or programmers.

    My 2 cents..

  4. 4 noctarius

    The clearest way to implement that kind of code is using the new try-with-resource pattern introduced in Java 7. A new fancy syntax has been added to the try construct.

    try (OutputStream out = new MyOutputStream(...) {
    //use the stream
    }

    The stream is automatically closed at the end of the try block. To use that feature from your own code / own implementations you just need to implement the new AutoCloseable interface (which is the new super interface of Closeable).

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Calendar

November 2011
M T W T F S S
« Sep   Dec »
 123456
78910111213
14151617181920
21222324252627
282930  

Follow me

twitter flickr LinkedIn feed

Subscribe by email

Enter your email address:

Archives


Categories

Tag Cloud


Listening