ExaSephiroth ExaSephiroth - 2 months ago 19
Java Question

Why can you throw a non occurring exception but not catch it

public void throwTest() throws SQLException, IOException {

} catch (SQLException e) {


Why is it that trying to catch an exception that will not occurr, will give a compilation error, whereas I can throw any Exception, it won't give an error? Both can be checked at compile time, so it would just make more sense to me if the behavior is the same?

In the given example, the catch-block will generate a compile time error:
error: exception SQLException is never thrown in body of corresponding try statement
} catch (SQLException e) {

When I remove the catch block, the code compiles just fine. This seems inconsistent to me.
Is there any particular reason for this behavior?


Catching can be determined at compile time. A throws declaration can be not actually thrown in the current method, but indeed in the overriden method of some child class. It is a contract for usage of the class in the form of child classes: it might throw that exception, and need to handle that one. It also allows the child class' method to throw that method.