• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception  RSS feed

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


i thought this program wont compile because we are invoking overriding method aMethod() on reference of base class and base class method declares Exception while Derived class method doesn't so compiler should complain here ? it is not ?

 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're always allowed to throw fewer (or more specific) exceptions in the overriding method. You aren't allowed to throw more (or more general) ones. The reason is that the second causes a problem, but the first doesn't.

With the second approach, you can have this happen:
If that was allowed, we could now do this:
The compiler would think that no exception is thrown and so would allow the second line (because the reference type is A), but then at runtime we get a checked exception thrown that isn't handled, and the compiler is supposed to guarantee that can't happen.

There's no such problem in your example. All that's happened is that you've been forced to handle an exception that it turns out can't be thrown by the subclass. But there's no danger in that, just a bit of redundant code.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!