gstackoverflow
gstackoverflow

Reputation: 37058

rethrowing exception handled in preceding catch block

on oracle ofiicial site write (http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html#rethrow)

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

-The try block is able to throw it.

-There are no other preceding catch blocks that can handle it.

-It is a subtype or supertype of one of the catch clause's exception parameters.

Please concentrate on second point (There are no other preceding catch blocks that can handle it. )

Research following code:

static private void foo() throws FileNotFoundException  {
        try {
            throw new FileNotFoundException();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw e;
        }
    }

This code compiles good. According my opinion after reading quote from mentioned article I expect to see that compiler will verify it and I will get compiler error.

Did I understand second point wrong?

Upvotes: 1

Views: 456

Answers (2)

Andres
Andres

Reputation: 10727

The throw e; line, effectively has no other preceding catch blocks that can handle it. It's true that a IOException could be a FileNotFoundException, but not on this particular case. If it were, it would have been caught by the first catch.

Upvotes: 0

russu
russu

Reputation: 34

This is perfectly fine because the FileNotFoundException is derived from IOException, and because you go from less specific to a more specific there should not be any issues.


edit:

static private void foo() throws FileNotFoundException  {
    try {
        throw new FileNotFoundException();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        throw e;
    }
}

Upvotes: 1

Related Questions