如何在单个案例中通过多个catch块进行异常处理?

Chr*_*ris 6 c++ inheritance exception-handling

假设您有以下层次结构.你有一个基类Animal,有一堆子类,如Cat,Mouse,Dog等.

现在,我们有以下场景:

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
   }
}
Run Code Online (Sandbox Code Playgroud)

所以,我想要的是,即使投掷了一只狗,我也希望执行Dog catch案例,还要执行Animal catch案例.你是怎么做到这一点的?

Jol*_*hic 9

另一个替代方法(除了try-within-a-try之外)是在一个从你想要的任何catch块调用的函数中隔离你的通用Animal处理代码:

void handle(Animal const & a)
{
   // ...
}

int main()
{
   try
   {
      ftn();
   }
   catch(Dog &d)
   {
      // some dog-specific code
      handle(d);
   }
   // ...
   catch(Animal &a)
   {
      handle(a);
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 最明显的东西有时候只能让我望而却步.:) (2认同)

Xeo*_*Xeo 7

AFAIK,你需要将它分成两个try-catch-blocks并重新抛出:

void ftn(){
   throw Dog();
}

int main(){
   try{
     try{
       ftn();
     }catch(Dog &d){
      //some dog specific code
      throw; // rethrows the current exception
     }catch(Cat &c){
      //some cat specific code
      throw; // rethrows the current exception
     }
   }catch(Animal &a){
    //some generic animal code that I want all exceptions to also run
   }
}
Run Code Online (Sandbox Code Playgroud)