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

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

    It means that if a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. For example:

    class A {
       public void foo() throws IOException {..}
    }
    
    class B extends A {
       @Override
       public void foo() throws SocketException {..} // allowed
    
       @Override
       public void foo() throws SQLException {..} // NOT allowed
    }
    

    SocketException extends IOException, but SQLException does not.

    This is because of polymorphism:

    A a = new B();
    try {
        a.foo();
    } catch (IOException ex) {
        // forced to catch this by the compiler
    }
    

    If B had decided to throw SQLException, then the compiler could not force you to catch it, because you are referring to the instance of B by its superclass - A. On the other hand, any subclass of IOException will be handled by clauses (catch or throws) that handle IOException

    The rule that you need to be able to refer to objects by their superclass is the Liskov Substitution Principle.

    Since unchecked exceptions can be thrown anywhere then they are not subject to this rule. You can add an unchecked exception to the throws clause as a form of documentation if you want, but the compiler doesn't enforce anything about it.

提交回复
热议问题