C++ 异常处理浅析

来源:互联网 发布:淘宝店铺买dnf账号 编辑:程序博客网 时间:2024/06/03 18:53

示例程序如下 :

#include <iostream>

using namespace std;

class expt
{
public :
 expt()
 {
  cout << " structor of expt " << endl;
 }
 ~expt()
 {
  cout << " destructor of expt " << endl;
 }
};

class demo
{
public :
 demo()
 {
  cout << " structor of expt " << endl;
 }
 ~demo ()
 {
  cout << " destructor of expt " << endl;
 }
};

void func1()
{
 int s = 0;
 demo d;
 throw s;
}

void func2()
{
  expt e;
  func1();
}

int main ()
{
 try {
  func2();
 } catch ( int )  {
  cout << " catch int exception " << endl;
 }
 cout  << " continue main() " << endl;
 return EXIT_SUCCESS;
}

 

运行结果:

structor of expt

structor of demo

destructor of demo

destructor of expt

catch int   exception

continue main()

 

运行结果分析:

 

在抛出异常之前创建了两个对象e和d, 在抛出异常之后,按照调用链的相反方向系统首先在func1返回的时候

调用局部对象d的析构函数~demo(),然后异常向上传递到函数func2 , 在func2 返回的时候调用局部对象e的

析构函数~expt() 。

 

 

 

原创粉丝点击