Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in Exception handling during inheritence

 
chandra mohan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I had just tried the below code but it gives compilation error.Could any one of you please explain me why?

I am declaring the exception which is defined in the super class.Why it is giving error in class T3 ? It is also subclass of T1 correct ?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
T3.t() overrides T2.t() and T2.t() is not declared to throw any Exception, so T3.t() cannot throw any checked exceptions.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Joanne has told you. A method can only declare a (checked) Exception if it is the same Exception its superclass method declares (or a subclass thereof).

You must be able to call the subclass method under the same conditions that you call the superclass method (as Barbara Liskov showed), so adding an Exception will violate those conditions.

T1#t declares two Exceptions, and is overridden by T2#t which tells the compiler it has managed to get rid of the Exceptions.
T3#t tries to override T2#t but tells the compiler it has new Exceptions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic