4

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?
RivieraKid
  • 5,923
  • 4
  • 38
  • 47
Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37

4 Answers4

9

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

Because of the substitution principle.

In short: because you shouldn't surprise users of the class hierarchy with new behavior.

This principle is common to all OO design/languages, not specific to Java.

Christian Garbin
  • 2,512
  • 1
  • 23
  • 31
2

An overriding class can add behavior and not remove. A method that declares to throw an exception - is a behavior.

Think what will happen if you have classes A and B extends A.
A implements foo() throws MyException, and B implements foo() throws OtherException

What will

A a = new B();
a.foo();

have to catch?

However, if B.foo() throws only a subset of the exceptions - it is still perfectly safe, the calling environment will catch (or declare as throwing) all of A's thrown exception - and by doing so - it will also deal with all of B's.

amit
  • 175,853
  • 27
  • 231
  • 333
2

Lets say it is possible to add new thrown exceptions in overridden methods.

class AA{
    void method() throws FileNotFoundException{}
}
class BB extends AA{
    @Override
    void method() throws FileNotFoundException, UnsupportedEncodingException {}
}   

Now you create reference AA to object BB and call method

AA a=new BB();
try {
    a.method();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Compilator will let you catch only FileNotFoundException exception, and wont allow to catch UnsupportedEncodingException because it is called from reference AA.

But you can add few types of exceptions to overridden method

  • if they are subtype of already thrown exception (IOException -> IOException, FileNotFoundException) because they will be checked,
  • if new exception doesn't have to be checked -> all RuntimeExceptions
Pshemo
  • 122,468
  • 25
  • 185
  • 269