mrbela
mrbela

Reputation: 4647

Why is it allowed to catch subtype of a thrown exception in Java

I read in a Java book, that "Java will not allow you to declare a catch block for a checked exception type that cannot potentially be thrown by the try class body".

That makes sense so far.

But now I am asking myself why this code does compile:

    try {
        throw new Exception();
    } catch (IOException e) {
    } catch (Exception e) {
    }

Java allows me to catch the IOException, but obviously it will never be thrown by the try-block.

Doesn't this example break the rule described in the Java book?

Upvotes: 2

Views: 858

Answers (2)

Maurice Perry
Maurice Perry

Reputation: 9651

It is obvious to a programmer that reads this code, but i guess the compiler will deal with the throw statement the same way it would deal with a call to a method declared as throwing Exception, and in this case, the thrown exception could very well be an IOException.

Upvotes: 3

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

Java allows me to catch the IOException, but obviously it will never be thrown by the try-block.

Because Exception is more general than IOException so the compiler understand that Exception can also be IOException.

Here is a contre example of what will happen if you try NumberFormatException instead of Exception

try {
    throw new NumberFormatException();
} catch (IOException e) {  // fail
} catch (Exception e) {
}

It fail because NumberFormatException is not general than IOException.

Upvotes: 6

Related Questions