Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

public void throwTest() throws SQLException, IOException {
    try{  
    } 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?

like image 231
ExaSephiroth Avatar asked Nov 22 '16 19:11

ExaSephiroth


1 Answers

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.

like image 196
Joop Eggen Avatar answered Sep 25 '22 16:09

Joop Eggen