c++inheritanceexception

How can you make exception handling fall through multiple catch blocks in a single case?


Let's say you have the following hierarchy. You have a base class Animal, with a bunch of sub classes like Cat, Mouse, Dog, etc.

Now, we have the following scenario:

void ftn()
{
   throw Dog();
}

int main()
{
   try
   {
       ftn();
   }
   catch(Dog &d)
   {
    //some dog specific code
   }
   catch(Cat &c)
   {
    //some cat specific code
   }
   catch(Animal &a)
   {
    //some generic animal code that I want all exceptions to also run
   }
}

So, what I want is that even if a Dog is thrown, I want the Dog catch case to execute, and also the Animal catch case to execute. How do you make this happen?


Solution

  • Another alternative (aside from the try-within-a-try) is to isolate your generic Animal-handling code in a function that is called from whatever catch blocks you want:

    void handle(Animal const & a)
    {
       // ...
    }
    
    int main()
    {
       try
       {
          ftn();
       }
       catch(Dog &d)
       {
          // some dog-specific code
          handle(d);
       }
       // ...
       catch(Animal &a)
       {
          handle(a);
       }
    }