Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) 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
Sheriff
Posts: 24215
37
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!
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!