File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes overriding rules Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "overriding rules" Watch "overriding rules" New topic

overriding rules

Rajiv Chelsea
Ranch Hand

Joined: Jun 15, 2010
Posts: 88
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

Joined: Sep 29, 2008
Posts: 12617

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

Joined: Jun 01, 2010
Posts: 618
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

Joined: Jun 15, 2010
Posts: 88
Hi Tom

Why dont the above rules apply for Runtime Exceptions?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

Because you don't need to catch them, or declare to throw them.

How To Ask Questions How To Answer Questions
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
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 ... ...

I agree. Here's the link:
subject: overriding rules
It's not a secret anymore!