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

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

    To understand this let's consider an example where we have a class Mammal which defines readAndGet method which is reading some file, doing some operation on it and returning an instance of class Mammal.

    class Mammal {
        public Mammal readAndGet() throws IOException {//read file and return Mammal`s object}
    }
    

    Class Human extends class Mammal and overrides readAndGet method to return the instance of Human instead of the instance of Mammal.

    class Human extends Mammal {
        @Override
        public Human readAndGet() throws FileNotFoundException {//read file and return Human object}
    }
    

    To call readAndGet we will need to handle IOException because its a checked exception and mammal's readAndMethod is throwing it.

    Mammal mammal = new Human();
    try {
        Mammal obj = mammal.readAndGet();
    } catch (IOException ex) {..}
    

    And we know that for compiler mammal.readAndGet() is getting called from the object of class Mammal but at, runtime JVM will resolve mammal.readAndGet() method call to a call from class Human because mammal is holding new Human().

    Method readAndMethod from Mammal is throwing IOException and because it is a checked exception compiler will force us to catch it whenever we call readAndGet on mammal

    Now suppose readAndGet in Human is throwing any other checked exception e.g. Exception and we know readAndGet will get called from the instance of Human because mammal is holding new Human().

    Because for compiler the method is getting called from Mammal, so the compiler will force us to handle only IOException but at runtime we know method will be throwing Exception exception which is not getting handled and our code will break if the method throws the exception.

    That's why it is prevented at the compiler level itself and we are not allowed to throw any new or broader checked exception because it will not be handled by JVM at the end.

    There are other rules as well which we need to follow while overriding the methods and you can read more on Why We Should Follow Method Overriding Rules to know the reasons.

提交回复
热议问题