2011-04-16 59 views
6

假設您有以下層次結構。您有一個基類的動物,跟一幫子類,如貓,鼠,狗等如何通過單個案例中的多個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 
    } 
} 

所以,我想的是,即使一條狗被拋出,我想要狗的抓住的情況下執行,並且動物抓住的情況下執行。你如何做到這一點?

回答

9

(從嘗試中之試除外)另一種方法是隔離的通用動物處理代碼中的函數從任何想要的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

7

據我所知,您需要拆分兩個的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 
    } 
}