Why can't overriding methods throw exceptions broader than the overridden method?

前端 未结 15 1507
梦谈多话
梦谈多话 2020-11-22 13:47

I was going through SCJP 6 book by Kathe sierra and came across this explanations of throwing exceptions in overridden method. I quite didn\'t get it. Can any one explain it

15条回答
  •  悲&欢浪女
    2020-11-22 14:49

    What explanation do we attribute to the below

    class BaseClass {
    
        public  void print() {
            System.out.println("In Parent Class , Print Method");
        }
    
        public static void display() {
            System.out.println("In Parent Class, Display Method");
        }
    
    }
    
    
    class DerivedClass extends BaseClass {
    
        public  void print() throws Exception {
            System.out.println("In Derived Class, Print Method");
        }
    
        public static void display() {
            System.out.println("In Derived Class, Display Method");
        }
    }
    

    Class DerivedClass.java throws a compile time exception when the print method throws a Exception , print () method of baseclass does not throw any exception

    I am able to attribute this to the fact that Exception is narrower than RuntimeException , it can be either No Exception (Runtime error ), RuntimeException and their child exceptions

提交回复
热议问题