Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why we are not allowed to declare a broader exception while overriding

 
rein dheer
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am learning java and OOPS. Could someone please explain why we are not allowed to declare broader exceptions, decrease the access level for method overridden in the subclass?

Thanks & Regards,
rein
 
Senthil Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rein !

For overriding methods following is a rule :

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. e.g. a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception or any other non-runtime exception unless it’s a subclass of FileNotFoundException.


Please also check this http://www.coderanch.com/t/250880/Programmer-Certification-SCJP/certification/please-confirm-about-overriding-exceptions
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As to why this is the case, an instance of a subclass should be able to be used anywhere an instance of a superclass is expected. (See: Liskov Substitution Principle). Client code might not even know (and should never care) that its dealing with an instance of a particular subclass, so how can it deal with an exception that it doesn't even know could be thrown?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic