Please help me on this, I'm unable to find out the reason why it is not getting compiled! It throws "must be caught or declared to be thrown a.eat()" error. Thanks.
class Animal
{
public void eat() throws Exception
{
System.out.println("Baseclass eat()");
}
}
class Dog extends Animal
{
public void eat() throws ArithmeticException
{
System.out.println("Subclass eat()");
}
}
class eg4psp
{
public static void main(String gg[])
{
try
{
Animal a = new Dog();
Dog d = new Dog();
a.eat();
d.eat();
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
}
}
You're calling a.eat()
, so as far as the compiler is concerned, any Exception
can be thrown - it only cares about the compile-time type of a
. (It doesn't reason that the value of a
is a reference to a Dog
, and Dog.eat
only throws ArithmeticException
.)
So in the code calling a.eat()
, you've either got to declare that that method (main
) throws Exception
, or catch it.
See more on this question at Stackoverflow