I have interface with abstract method, that throws checked exception and class that implements that interface and method.
Am I obligated to declare that implemented method throws exception mentioned in interface declaration?
Because a class that implements the interface might thrown the given exception. A overridden method can't throw a new or broader checked exception.
Joined: Apr 15, 2009
Sorry, but I cannot see how your post answers on my question.
Consider following code:
ClassB implements TestInterface, so I have to implement doIt method. But I do not have to declare that this method throws IOException.
Class A initializes ClassB and I can invoke doIt method without handling exception.
So why should I ever need to declare in interface that doIt method throws exception?
Joined: Feb 23, 2009
Imagine that one of your implementer classes need to throw an exception:
The avobe code don't compile, due to an overriding/implementing method CAN'T THROW a new or broader checked exception. So, you declare the exception in the interface, and later choose either throw or not throw such exception in a implementer class. The key point is that if you don't declare the exception in the base class, a subclass can't never throw such a exception if needed.
My fault. The method signatures were legal overrides but you can only have one legal override per method and I had three.
I just copied the above out of eclipse. Same method signatures but different classes.
Joined: Apr 15, 2009
I get the point. Thank you for explanations.
My next question is such freedom to choose can impose issues?
Let’s take class that implements TestInterface (ClassB) and exception thrown on the doIT method.
Any usage of this method (ClassA) will obligate to catch declared exception, right?
Later I can review my ClassB and decide that I do not want to throw exception. I am allowed to.
What will happened with ClassA(assuming it is not going to be recompiled), that still tries to catch exception that never thrown?
The rule for overriding method is that: you cant declare broader or new checked exception for overriden method RuntimeException or any of its subtype are considered as unchecked exception. So there is no problem in declaring new or broader exceptions.
Note that overriden rule is applied to only checked exception