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

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

    The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method.

    This simply means when you override an existing method, the exception that this overloaded method throws should be either the same exception which the original method throws or any of its subclasses.

    Note that checking whether all checked exceptions are handled is done at compile time and not at runtime. So at compile time itself, the Java compiler checks the type of exception the overridden method is throwing. Since which overridden method will be executed can be decided only at runtime, we cannot know what kind of Exception we have to catch.


    Example

    Let's say we have class A and its subclass B. A has method m1 and class B has overridden this method (lets call it m2 to avoid confusion..). Now let's say m1 throws E1, and m2 throws E2, which is E1's superclass. Now we write the following piece of code:

    A myAObj = new B();
    myAObj.m1();
    

    Note that m1 is nothing but a call to m2 (again, method signatures are same in overloaded methods so do not get confuse with m1 and m2.. they are just to differentiate in this example... they both have same signature). But at compile time, all java compiler does is goes to the reference type (Class A in this case) checks the method if it is present and expects the programmer to handle it. So obviously, you will throw or catch E1. Now, at runtime, if the overloaded method throws E2, which is E1's superclass, then ... well, it's very wrong (for the same reason we cannot say B myBObj = new A()). Hence, Java does not allow it. Unchecked exceptions thrown by the overloaded method must be same, subclasses, or non-existent.

提交回复
热议问题