• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exceptions and overriding  RSS feed

 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When a method is overridden, should the overriding method throw the same exceptions that the overridden one throws? If yes,why?
 
chandraiah chintakayalu
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
yes it can throw same Exception class and any subclass of the thrown Exception
and it can throw any unchecked Exception too..

correct me if im wrong..
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No.. i m not asking whether it CAN throw exceptions, SHOULD it throw the same exception?
 
Sudhakar Duraiswamy
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rakesh,
Not necessarily.All the Exception (that are of same type/sub class of the Method that is overridden)
need not be metioned as part of the method signature and it is not mandatory that the exception of that type
should be thrown.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is always legal, and quite often appropriate, for a subclass method to declare that it throws fewer exceptions than the superclass method it overrides.

For example, imagine that Superclass has an abstract method getData(). Because the Superclass implementor expects some implementations to involve file reading, it is declared to throw IOException. But say someone implemets a subclass that gets the data from a String. Reading a String will not cause an IOException, so the method in this subclass should not declare that it throws IOException.
 
rakesh sugirtharaj
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks peter, sudhakar.. But i suppose if the child method throws exception the parent has to, too.... rite?
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A subclass cannot declare that it throws checked exceptions that the superclass does not throw. It's a compile-time error if you try to do so.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!