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?
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?
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.
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?
I have discovered a strange thing while studying the interfaces part. Consider the following code:
Why does this code compile? ClassCastException is at the same level in the inheritance tree as IllegalArgumentException. They are both a direct subclass of RuntimeException. So they don't have a IS-A relationship with each other. And look at this:
IllegalArgumentException is a subclass of RuntimeException, so RuntimeException is a broader exception! So, why does this compile?
I hope someone is able to help me with this. I have installed Java version 1.6.0_17
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