简体   繁体   中英

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?

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.

I'm not sure I understand your question but I'll take a stab at it. The compiler is trying to help you avoid a mistake. If you had code in your try block that throws SQLException but your catch block had a typo and you were catching SLQException then you would want the compiler to flag that error. That's why it flags this as an error, the exception you're catching is never thrown.

I think the second part of your question is, why are you allowed to put whatever you want in the throws clause of your method declaration regardless of whether the method actually throws that exception? I think there are two reasons. First, the method declaration is an interface and it tells clients how to code to it. You may set up the method declaration and make it available to your co-workers before you complete the method body. So in that case it's not an error, just a work in progress. Second, your class may implement an interface which declares the method as throwing an exception but in your particular implementation you don't need throw it. Again, that's not an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM