2011-09-23 125 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块中调用析构函数?