问题描述
|
假设您具有以下层次结构。您有一个基类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
}
}