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

mrbela :

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?

Maurice Perry :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111797&siteId=1