Why this overridden method cannot throw a new checked exception

I have two questions:

  • What is the purpose of limiting that an overridden method cannot throw a new thrown exception?
  • Why is it allowed that an overridden method can only throw all or nothing or a subset of the checked exceptions that are specified in the throws clause of the overridden method in the superclass?
+4
source share
4 answers

In both cases, this is because the base method that you override has set up a contract with a call code; if you could add to the checked exceptions that the method may throw, you will break the contract.

Consider the Base class with the foo method, which throws a SomeException . You also have Derived , which comes from Base and overrides foo . The code in the App uses the Base b variable, but initializes it with a new Derived instance and calls b.foo() . The contract is that foo throws only SomeException ; throwing anything else violates the contract.

+8
source

An overriding class may add behavior and not delete. A method that declares an exception is called behavior.

Think about what happens if you have classes A and B extends A
A implements foo() throws MyException , and B implements foo() throws OtherException

What will happen

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

need to catch?

However, if B.foo() throws only a subset of the exceptions - it is still completely safe, the calling environment will catch (or declare as throwing) the entire exception A , and thus it will also be with all B.

+2
source

Due to the principle of substitution .

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

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

+2
source

Suppose you can add new excluded exceptions to overridden methods.

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

You are now creating an AA link for the BB object and call method

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

The compiler will only allow you to catch a FileNotFoundException and will not catch a UnsupportedEncodingException because it is called from an AA reference.

But you can add several types of exceptions from an overridden method

  • if they are a subtype of an already generated exception ( IOException IOException, FileNotFoundException ) because they will be checked,
  • If a new exception does not need to be checked -> all RuntimeException s
+2
source

Source: https://habr.com/ru/post/1416345/


All Articles