Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception while overriding

 
suresh sai
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,please resolve the problem of exception for overriding.Actually ,if super class declares a checked exception,then the overriding method cannot declare a new exception,or a cheked exception of broader type.

But the following gives error;
class A
{
void method() throws Exception
{

}

}

class B extends A
{
void method()
{

}

}
In the above scenario,the overriding method cannot declare a new exception or a checked exception of broader type ,But it is showing the error.Please solve this problem.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nothing wrong with this code; it would compile fine. Have you remembered to PostRealCode?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your description rings true but there was something missing from your example. Let's say you wrote class A:

And I started using it:

You told me to handle IOException and I did. What if the compiler let somebody write a new class B:

And what if somebody passed an instance of B into my method? I'd be totally unprepared to handle a SQLException because A never told me it might happen. That would be bad enough that the compiler just doesn't let you write B that way.

There's a neat guideline called the Liskov Substition Principle that says if B extends A then any code that works with an instance of A should work equally well with an instance of B. Throwing unexpected exceptions would certainly break that rule!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic