Overridden methods cannot throw exceptions Java

Subclass overriden method/methods can throw (Declare) only unchecked exception like ArrayIndexOutOfBoundsException.

But you can't throws (declare) the checked exception. like IOException.

example to overridden methods throw exceptions Java

class A{
 public void show(){
   // some code here
  }
}

class B extends A{
public void show() throws ArrayIndexOutOfBoundsException{
   // some code here
  }
}

Hope these may help you.


Overridden methods can throw Exceptions, so long as the method being overridden also throws the same Exceptions. You can't introduce new Exceptions.

So why can't you introduce a new Exception?

One of the central concepts of OOP is using abstract types, and that all subtypes may be treated as the abstract type. See Liskov Substitution Principle

The reason you can't introduce broader behaviour is that if the method from the abstract type (super class or interface) doesn't throw an Exception and you refer to your object as that type, you'd get unexpected behaviour:

Alpha alpha = new Beta();
// At this point, the compiler knows only that we have an Alpha
alpha.myMethod();

If Alpha's myMethod() doesn't throw an Exception, but Beta's does, we could get an unexpected Exception in the above code.


Your client side always think to deal with the base version. That's the whole benefit of polymorphism => client side ignores the overriden one.

Thus, nothing will force the client to deal with specific rules made by the overriden, here the case of a potential exception thrown by the overidden method.

That's why an overriden method can't throw broader exceptions. It would break the contract.

Thus, regarding this logic, rule is: Overriden method CAN (if it want) only throw a subpart of the exceptions declared in the base version BUT CANNOT throw broader ones.

Tags:

Java