A question about Exception inheritance

Discussion in 'Java' started by www, Oct 18, 2007.

  1. www

    www Guest

    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.
    www, Oct 18, 2007
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. maxw_cc
    Replies:
    1
    Views:
    3,117
    Martijn van Steenbergen
    Dec 21, 2003
  2. cppsks
    Replies:
    0
    Views:
    803
    cppsks
    Oct 27, 2004
  3. www
    Replies:
    5
    Views:
    307
    Daniel Pitts
    Nov 12, 2007
  4. www
    Replies:
    0
    Views:
    254
  5. barcaroller
    Replies:
    5
    Views:
    587
    James Kanze
    Jul 19, 2009
Loading...

Share This Page