Why you can throw an exception but not catch it

public void throwTest() throws SQLException, IOException { try{ } catch (SQLException e) { } } 

Why is he trying to catch an exception that does not happen, will give a compilation error, while I can throw any exception, it will not give an error? Both can be checked at compile time, so would it make more sense to me if the behavior were the same?

In this example, the catch block generates a compile-time error: error: A SQLException is never thrown into the body of the corresponding try} catch statement (SQLException e) {

When I delete the catch block, the code compiles just fine. It seems inconsistent to me. Is there any special reason for this behavior?

+5
source share
2 answers

A trap can be defined at compile time. The throw declaration may not actually be selected in the current method, but indeed in the overriden method of some child class. This is a contract to use the class as child classes: it can throw this exception and must handle it. It also allows a child class method to use this method.

+3
source

I'm not sure I understand your question, but I will take a hit on him. The compiler is trying to help you avoid errors. If you had code in a try block that throws a SQLException, but your catch block had a typo and you caught a SLQException, then you would like the compiler to flag this error. Therefore, he puts it as an error, the exception you catch is never thrown.

I think the second part of your question is: why can you put whatever you want into the throws clause of your method declaration, regardless of whether the method actually throws this exception? I think there are two reasons. First, a method declaration is an interface and tells clients how to code it. You can customize the method declaration and make it available to your employees before filling out the method body. Therefore, in this case, this is not a mistake, but only incomplete work. Secondly, your class can implement an interface that declares a method as an exception, but in your specific implementation you do not need to throw it. Again, this is not a mistake.

+2
source

Source: https://habr.com/ru/post/1260162/


All Articles