A question about Exception inheritance

W

www

Hi,

I have three classes(Animal, Dog and Cat). For them, I have created
three kinds of Exception class too:

AnimalException, DogException and CatException.

Animal is the superclass of Dog and Cat.

AnimalException, a subclass of Exception, is the superclass of
DogException and CatException.

public class Animal
{
public void doIt() throws AnimalException
{
if(..)
{
throw new AnimalException(getClass().getName() + " screwed up.");
}
}
}


public class Dog extends Animal
{
public void doIt() throws DogException
{
super.doIt(); //oops, wrong!
}
}

The message says that the AnimalException is not handled. I understand
it. So I have to do it:

public class Dog extends Animal
{
public void doIt() throws DogException
{
try
{
super.doIt();
}
catch(AnimalException e)
{
throw new DogException(e.getMessage()); //take the message, re-throw
it again.
}
}
}

I feel this is really pain and un-necessary. Since I run into such
patterns many times, I am wondering if anybody could help me out.

Is that wrong to have DogException and CatException? Should I just keep
AnimalException and replace DogException with AnimalException?

Thank you very much.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top