java - checked exception for 'throws' in overridden method

后端 未结 2 820

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:32

    There are two related errors in the sample:

    1) Your base class method provides the "template" or basic criteria for the derived class method.

    So, the base class should declare a super-set i.e. either the same exception class or base exception class of the derived class. You cannot declare that it throws nothing, because then the criteria will not match.

    So if your derived class method is like this:

    class Derived extends Base {
        void show() throws IOException {
            //...
        }
    }
    

    Then base class method "must" be:

    class Base {
        void show() throws /*Same or base classes of IOException*/ {
            //...
        }
    }
    

    So both of these work:

    class Base {
        void show() throws Exception {
            //...
        }
    }
    

    or

    class Base {
        void show() throws Throwable {
            //...
        }
    }
    

    2) When you try the above, the overall declaration of your show method now becomes throws Exception. As a result, anyone who uses this show must catch that exception.

    In your main method, you are catching IOException. This will no longer work, the compiler complains "ok you are catching the IOException, what about all the other possibilities from Exception?" This is the second error that you showed.

    To fix this, change the main method catch to include Exception as declared in the base class:

    class My {
        public static void main(String[] args) {
            try {
                base b = new derived();
                b.show();
            }
            /* NOTE: CHANGED FROM IOException TO Exception */
            catch (Exception e) {
                System.out.println("exception occurred at :" + e);
            }   
        }
    }
    

提交回复
热议问题