Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions

 
Neil Muya
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Just want to clarify something with Exception:



In this code a.eat() calls the eat method of Frog not Animal.

Then why does a.eat() gives a compile error that it should Handle/Declare?

Maybe there is a rule I'm missing . Hope you could help me.


Thanks in Advance!
 
Simran Dass
Ranch Hand
Posts: 183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Compiler checks the reference type of the variable. In case of overriding which method
will be called is decided at runtime. In the line :

Animal a = new Frog();

Compiler sees that a is of type Animal . But the eat() method in class Animal throws Exception
which is neither handled nor declared in the place from where its called ( main() method here). Hence you get a Compiler error . eat() of Frog class is called at runtime but befor that
compiler checks the method in the class of the reference type which is Animal here
 
Neil Muya
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ow okay , Got it . Thank You Simran!
 
Jeevan Reddy
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simran Dass wrote:

Compiler checks the reference type of the variable. In case of overriding which method
will be called is decided at runtime. In the line :

Animal a = new Frog();

Compiler sees that a is of type Animal . But the eat() method in class Animal throws Exception
which is neither handled nor declared in the place from where its called ( main() method here). Hence you get a Compiler error . eat() of Frog class is called at runtime but befor that
compiler checks the method in the class of the reference type which is Animal here


Thanks for the info Simran. That helped me too.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic