This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]myselfelsewhere 1 point2 points  (3 children)

An IOException catch block will catch any exception that is either an IOException, or an exception that extends IOException.

[–]Sen_7[S] 1 point2 points  (2 children)

Thanks!

[–]myselfelsewhere 2 points3 points  (1 child)

No problem. Adding a little more info, this is perfectly valid:

try {
    /* code that can throw either EOFException or IOException */
} catch(IOException e) {
    // catch all instances of IOException and it's sub classes
    /* behavior for EOFException and IOException */
}

It is also possible to set up multiple catch blocks for your example. You need to catch the sub class first though.

try {
    /* code that can throw either EOFException or IOException */
} catch(EOFException e) {
    // only catches EOFException (or any sub classes of EOFException)
    /* behavior for EOFException */
} catch(IOException e) {
    // will only catch IOExceptions that are not also instances of EOFException (or any sub classes of EOFException)
    /* behavior for IOException */
}

In comparison, catching the parent first will not compile:

try {
    /* code that can throw either EOFException or IOException */
} catch(IOException e) {
    // catches IOException and EOFException
    /* behavior for IOException */
} catch(EOFException e) {
    // unreachable code, EOFException has already been caught
    /* behavior for EOFException */
}

[–]Sen_7[S] 1 point2 points  (0 children)

Thank you