2012-04-07 54 views
0

我正在嘗試調用終止函數。 [我認爲這個函數在堆棧展開過程中出現另一個異常時被調用]。我編寫並試圖驗證的相同場景。異常處理相關

我能夠看到一個調用正在終止()函數,但我不知道爲什麼我geting調試錯誤。

當試圖在Visual Studio 2008中執行以下代碼時,出現錯誤消息對話框「調試錯誤」。也被顯示在輸出:

輸出:

在try塊

在甲

構造在乙

的構造在B的析構函數

A

的析構函數

致電my_terminate

爲什麼在執行此代碼時出現此「調試錯誤」窗口?這是預期的行爲?如何消除這個錯誤?

class E 
{ 
public: 
     const char* message; 
     E(const char* arg) : message(arg) { } 
}; 
void my_terminate() 
{ 
     cout << "Call to my_terminate" << endl; 
}; 

class A 
{ 
public: 
     A() { cout << "In constructor of A" << endl; } 
     ~A() 
     { 
      cout << "In destructor of A" << endl; 
      throw E("Exception thrown in ~A()"); 
     } 
}; 

class B 
{ 
public: 

     B() { cout << "In constructor of B" << endl; } 
     ~B() { cout << "In destructor of B" << endl; } 
}; 

void main() 
{ 
     set_terminate(my_terminate); 

     try 
     { 
     cout << "In try block" << endl; 
     A a; 
     B b; 
     throw("Exception thrown in try block of main()"); 
     } 
     catch (const char* e) 
     { 
     cout << "Exception: " << e << endl; 
     } 
     catch (...) 
     { 
     cout << "Some exception caught in main()" << endl; 
     } 

     cout << "Resume execution of main()" << endl; 
     getch(); 
} 

回答

3

您從~A()拋出異常。從析構函數中拋出異常是很危險的。如果另一個異常已經傳播,應用程序將終止。有關更詳細的描述,請參閱https://stackoverflow.com/a/130123/72178

爲什麼在執行此代碼時出現此「調試錯誤」窗口?

您正在從try區塊向main投擲異常。這將調用「堆棧展開」並調用AB的析構函數。當從~A()應用程序終止引發異常時。

它是預期的行爲?

是的,它由標準定義。

如何移除該錯誤?

不要從析構函數中拋出。

+0

我很確定問題是「爲什麼不是那個異常在catch塊中被捕獲?」 – Mat 2012-04-07 07:36:55