java - checked exception for 'throws' in overridden method

后端 未结 2 821

I was practicing exception handling mechanisms with method overriding in java...My code is as follows:

class base {
    void show() {    
        System.out.p         


        
2条回答
  •  渐次进展
    2020-12-20 06:36

    Overridden methods may contain only the same checked exceptions in their throws clause as the super-method, or derived types at most.

    For example if you say

    class Base {
    
        public void foo(int y) throws IOException {
            // ...
        }
    }
    

    and

    class Derived extends Base {
    
        public void foo(int y) throws Exception {
            // ...
        }
    }
    

    then your compiler will say that the foo method inside Derived is incompatible with the throws clause in its superclass.

    The other way around works because if I say

    class Base {
    
        public void foo(int y) throws Exception {
            // ...
        }
    }
    

    and

    class Derived extends Base {
    
        public void foo(int y) throws IOException {
            // ...
        }
    }
    

    it's OK.

    Why.

    Think about the usage of your methods. Java expects you to be using the method polymorphically such as

    Base a = new Derived();
    a.foo(3);
    

    As such, the compiler will force you to catch the exception thrown by foo in your declared type of the variable (Base). So your code will become

    Base a = new Derived();
    try {
        a.foo(3);
    } catch (Exception e) {
        // ...
    }
    

    Therefore, the subtype of Exception you declared in the Derived type is OK with your code above (a catch for an Exception will work for any of its subtypes as well) and as such, Java will allow you to declare IOException in derived, because it will cause no worries later on.

提交回复
热议问题