The overriding method in the inherited class must
throw fewer or narrower exceptions but not broader exception than the method that is being overridden.
May I know the intention behind this rule?
The overriding method in the inherited class must
throw fewer or narrower exceptions but not broader exception than the method that is being overridden.
May I know the intention behind this rule?
Overridden methods cannot throw newer or broader checked exception just because, when the object of this class is referred polymorphic-ally, the caller can handle only exceptions shown in the contract by the base class method implementation.
Overridden method can throw unchecked exception in case if parent method throws it or not. You can even not declare it in signature. But if parent method throws checked exception you can only specialize this exception in the child (throw same exception, it's descendants or none).
Refer this link for better understanding : http://www.javatpoint.com/exception-handling-with-method-overriding
A Child class must be able to behave as if it were the parent class; when calling a parent class method that throws (for example) IOExceptions
you do not expect to suddenly recieved OtherException
.
For example
public class ParentClass {
public void doSomething() throws IOException{
}
}
public class ChildClass extends ParentClass{
@Override
public void doSomething() throws IOException, CustomException{
super.doSomething();
}
}
When we use the parent class to call doSomething() we are obliged to deal with IO exceptions
public static void main(String[] args){
ParentClass p=new ChildClass(); //child class behaving as parent
try {
p.doSomething();
} catch (IOException ex) {
Logger.getLogger(ChildClass.class.getName()).log(Level.SEVERE, null, ex);
}//no catch for secret CustomException that the ChildClass can throw
}
But you can see that there is a secret CustomException
that could be thrown that we haven't dealt with (but as CustomException
isn't a runtime exception it shouldn't be possible to have it thrown without the methods higher in the stack knowing about it or dealing with it)
it means that if you're overriding a method that throws an exception, it can only throw an exception that is the same as the super method throws or is an exception that extends the exception from the superclass (throws less if you will).