Base Class Reference throws Exception and Subclass does not
Method in Parent Class throws an exception and the method in the subclass does not.
When a reference variable of the base class (in this case Mammal) is used to invoke a method of the subclass (Human) using polymorphism,
and the method in the Base Class throws an exception but the method in the Subclass does not, the method call needs to be wrapped in a try catch block.
In the example below, you will receive a compiler error on line1 because the method eat() in the base class Mammal throws an exception and you are using a reference variable of the Base Class.
Although the actual method that is called in the Subclass does not throw an exception,
the compiler still requires you wrap the call to the method in a try-catch block because the reference variable being used is of the
Parent Class, and the method eat() in the Base Class throws an exception.
Example 1: Base Class Mammal and subclass Human
public class Mammal {
public void eat() throws Exception {
System.out.print("Mammal Eats");
}
public static void main(String[] args) {
Mammal m1 = new Human();
// m1.eat(); //line 1
try { // line 2
m1.eat();
} catch (Exception e) {
e.printStackTrace();
}
Human h1 = new Human();
h1.eat();;
}
}
class Human extends Mammal{
public void eat() {
System.out.print("Human Eats");
}
}