Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding rules

 
Rajiv Chelsea
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the logic behind the exceptions which can be declared by an overriding method?

Like it cant declare any new or broader checked exceptions , but can declare any runtime exceptions..
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anything can throw a RuntimeException at any time--no restrictions are necessary, nor is it necessary to declare it in the "throws".

If you were able to declare additional checked exceptions then you would no longer be following the "contract" of the original method--code that calls it shouldn't have to change if it starts using a subclass implementation.
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like it cant declare any new or broader checked exceptions

Because if you create an instance of class B which extends A, store it in a reference to A, and then call B's overridden methods, the compiler would not be able to recognize that the overridden functions in B are throwing the new or broader exceptions.
 
Rajiv Chelsea
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom

Why dont the above rules apply for Runtime Exceptions?
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you don't need to catch them, or declare to throw them.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From a design perspective, you should also worry about runtime exceptions.
Just because the compiler allows something does not mean that it should be
done. For example, consider invalid downcasts.

Think about code already in service that uses the method you want to override;
a method that throws MyException. During program checkout, it was verified that
MyException was properly handled. For the revised method, following the Is-A rule,
the catch clause that handles MyException will also handle an extension of it, if you
create one. But it may not catch a new exception type, runtime or otherwise. So you
will have broken the application error handler.

Jim ... ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic