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

前端 未结 15 1406
梦谈多话
梦谈多话 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:43

    The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception

    Example:

    class Super {
        public void test() {
            System.out.println("Super.test()");
        }
    }
    
    class Sub extends Super {
        @Override
        public void test() throws IndexOutOfBoundsException {
            // Method can throw any Unchecked Exception
            System.out.println("Sub.test()");
        }
    }
    
    class Sub2 extends Sub {
        @Override
        public void test() throws ArrayIndexOutOfBoundsException {
            // Any Unchecked Exception
            System.out.println("Sub2.test()");
        }
    }
    
    class Sub3 extends Sub2 {
        @Override
        public void test() {
            // Any Unchecked Exception or no exception
            System.out.println("Sub3.test()");
        }
    }
    
    class Sub4 extends Sub2 {
        @Override
        public void test() throws AssertionError {
            // Unchecked Exception IS-A RuntimeException or IS-A Error
            System.out.println("Sub4.test()");
        }
    }
    

提交回复
热议问题