Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Method overriding (K & B Pg.no. 104)  RSS feed

 
Amit Sethi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q. why this code is giving error ? (K & B Pg.104)

class Animal {
public void eat() throws Exception {
}
}
class Dog extends Animal {
public void eat() {
}
}

class Pg104 {
public static void main(String args[]) {
Animal ob1 = new Dog();
Dog ob2 = new Dog();
ob1.eat();
ob2.eat();
}
}

Error:

F:\j5se\kathy>javac Pg104.java
Pg104.java:14: unreported exception java.lang.Exception; must be caught or declared to be thrown
ob1.eat();
^
1 error


( what i have read is if throws clause is given with the function then it means the function is going to produce this type of exception & it should be handeled in this function or in it's caller's )


pls help me, i need the full explaination of this error's cause & how it can be corrected ?

Thanks in advance.

Regards
Amit Sethi.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Animal.eat() might throw an Exception object; therefore, any code that calls eat() on a reference variable of type "Animal" must either include a try/catch block to catch the Exception, or must be in a method that itself declares that it throws Exception.

So you must either surround the call to ob1.eat() with a try/catch, or modify the declaration of main() to include "throws Exception."
 
Amit Sethi
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Ernest.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!