如何通过单个案例中的多个catch块实现异常处理?

问题描述:

假设您有以下层次结构。您有一个基类的动物,跟一帮子类,如猫,鼠,狗等如何通过单个案例中的多个catch块实现异常处理?

现在,我们有以下情形:

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 
    } 
} 

所以,我想的是,即使一条狗被抛出,我想要狗的抓住的情况下执行,并且动物抓住的情况下执行。你如何做到这一点?

(从尝试中之试除外)另一种方法是隔离的通用动物处理代码中的函数从任何想要的catch块中调用:

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

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

最明显的东西有时会忽略我。 :) – Xeo 2011-04-16 00:48:36

据我所知,您需要拆分两个的try-catch块,并重新抛出:

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 
    } 
}