2011-09-23 124 views
3
#include<iostream> 
using namespace std; 
class test 
{ 
    public: 
     test() 
     { 
      cout<<"hello";} 
      ~test() 
      { 
       cout<<"hi"; 
       throw "const"; 
      } 
      void display() 
      { 
       cout<<"faq"; 
      } 
}; 
int main() 
{ 
    test t; 
    try{ 
    } 
    catch(char const *e) 
    { 
     cout<<e; 
    } 
t.display(); 
} 

輸出:output:如何處理異常?

我知道從析構函數拋出例外,我正在違反基本的C++的法律但我仍想知道的是他們的任何方式異常可以被處理。

try 
{ 
test t; 
t.Display(); 
} 

和完整版: - catch塊 - t

#include<iostream> 
using namespace std; 

class test 
{ 
    public: 
     test() 
     { 
      cout << "hello" << endl; 
     } 

     ~test() 
     { 
      cout << "hi" << endl; 
      throw "const"; 
     } 
     void display() 
     { 
      cout << "faq" << endl; 
     } 
}; 

int main() 
{ 
    try 
    { 
     test t; 
     t.display(); 
    } 
    catch(char const *e) 
    { 
     cout << e << endl; 
    } 
} 
+0

所以,除了這個小例子之外,你真正想要完成什麼?因爲這感覺就像你做錯了... – Chad

回答

4

你的try外析構函數運行

+0

我不能在try塊中聲明test t,因爲我想要t.display來執行。 –

+2

在'try'-'catch'中也調用'display()'? –

3

測試對象的創建必須try塊內完成範圍是main函數。但是然後從析構函數中引發異常是Bad IdeaTM

+0

我不能,因爲我想t.display也執行。 –

+0

好的,我添加了對Display()的調用。 – Jem

+0

選中此版本。它顯示「hello」,「faq」,「hi」和「const」。 – Jem

3

你的try塊沒有任何東西。試試這個:

try 
{ 
    test t; 
} 
catch(char const *e) 
{ 
    cout << e; 
} 

另外,一般在析構函數拋出異常是一個壞主意(與大多數的規則,也有例外)。

+1

我不能,因爲我想t.display也執行。通過使用試驗 測試t; } 我使本地嘗試塊,這將彈出錯誤。 –

+0

@ desprado07:將呼叫也顯示在try-block中。 – Steve

1

爲什麼不直接在try塊中調用析構函數?