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 Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception" Watch "Exception" New topic


abalfazl hossein
Ranch Hand

Joined: Sep 06, 2007
Posts: 635

When you are deriving classes an overridden method cannot throw a exception greater then that
declared for the original method. A greater exception is the super exception class of a sub exception
class. Notice we have two hierarchies. The classes that you are defining and the exception classes
they are using. This means if a super class method throws a super class exception (SE) then a sub
class method can only through a super class exception (SE) or a sub class exception (SubE)

May you explain about override exception and INHERITING EXCEPTIONS?
greg buela
Ranch Hand

Joined: Sep 04, 2007
Posts: 71
Consider this:

That is what that quote says you can't do.
The overriding method must declare to throw the original exception (as declared in the overriden method: SubException in the example), an exception that is derived from it, or no exception at all. My example is wrong because it declares to throw Exception, which is a base class to SubException.
This rule is necessary because of polymorphism. Somebody might be calling the method in the subclass (MyDerived) through a base class reference (MyBase). They will only be aware of whatever is declared to be thrown in the base version of the method. So code like this:

would be unaware of any thrown Exception that is not SubException or derived!

SCJP 1.5
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46349
A general rule in inheritance: you should be able to use the subclass exactly as you would use the superclass without any surprises. This is attributed to Barbara Liskov.
If you declare an exception in a subclass method which isn't thrown in the superclass, then you have to use the subclass differently from the superclass. So you are not inheriting correctly. So you can only throw an exception in the subclass which is already declared in the superclass. If you have a superclass method which might throw XYZException in a subclass, you have to write "throws XYZException" in the superclass too.
I agree. Here's the link:
subject: Exception
It's not a secret anymore!