Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it that an overridden method can't throw a new checked Exception [duplicate]

Tags:

java

I have two questions :

  1. What is the purpose of the constraint that an overridden method can't throw a new checked exception?
  2. Why it is allowed that an overridden method can only throw all or none, or a subset of the checked exceptions that are specified in the throws clause of the overridden method in the superclass?
like image 502
Pramod Kumar Avatar asked Dec 05 '22 16:12

Pramod Kumar


1 Answers

In both cases, it's because the base method you're overriding has set the contract with the calling code; if you could add to the checked exceptions that the method may throw, you'd be breaking the contract.

Consider a class Base with a method foo that throws a checked exception SomeException. You also have a Derived which derives from Base and overrides foo. Code in App is using a Base b variable but initializing it with a new instance of Derived, and calling b.foo(). The contract is that foo throws just SomeException; throwing anything else breaks the contract.

like image 133
T.J. Crowder Avatar answered Dec 21 '22 23:12

T.J. Crowder