如何在单个案例中使异常处理跨越多个catch块?

问题描述

| 假设您具有以下层次结构。您有一个基类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
   }
}
所以,我想要的是即使抛出一条狗,我也要执行Dog捕获程序,并且还要执行Animal捕获程序。您如何做到这一点?     

解决方法

另一个选择(除了try-within-a-try之外)是在一个函数中隔离您的通用动物处理代码,该函数从您想要的任何catch块中调用:
void handle(Animal const & a)
{
   // ...
}

int main()
{
   try
   {
      ftn();
   }
   catch(Dog &d)
   {
      // some dog-specific code
      handle(d);
   }
   // ...
   catch(Animal &a)
   {
      handle(a);
   }
}
    ,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
   }
}
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...