天天看点

构造函数抛出异常

    构造函数抛出异常有两种:

    (1)一种是在初始化列表里抛出,这种情况应该捕获,进行回滚,然后系统自动上抛,在上层还应该catch一次。这时,构造未完成,故析构函数不被调用。

    (2)另一种是在函数体中抛出异常,这种系统是不会自动上抛的。这种情况构造已经完成,会调用析构函数。

    当然,最好是不要在构造函数里干太多事,大可以拿一个init函数来手动调用。。。

    测试:

#include <iostream>
using namespace std;
void f2();
void f1();

class X 
{
public:

	X()
	{
		try
	    {
            cout<<"X()"<<endl;
	        throw 1;
	    }
	    catch(...)
	    {
	        cout<<"X() catch"<<endl;
	    }
	}
	
	X(int x)try
    {
        cout<<"X(int)"<<endl;
	    throw 1;   
	}
	catch(...)
	{
	    cout<<"X(int) catch"<<endl;
	}
	
	
    ~X() 
    {
	    cout << "~X\n";
         
    }
};

int main()
{
///1
  cout<<"1"<<endl;
  try 
  {
    X x(1);
  }
  catch(...)
  {
    cout<<"main catch"<<endl;
  }
  
  cout<<"2"<<endl;
///2
  try 
  {
    X x;
  }
  catch(...)
  {
    cout<<"main catch"<<endl;
  }
  
  
  cout<<"f1"<<endl;
  f1();
  cout<<"f2"<<endl;
  f2();


}



/

void f2()
try
{
    throw 1;
}
catch(...)
{
    cout<<"f2:catch"<<endl;
}

void f1()
{
    try
    {
        throw 1;
    }
    catch(...)
    {
        cout<<"f1:catch"<<endl;
    }
}
           

[email protected]:~$ g++ d.cpp -o d

[email protected]:~$ ./d

1

X(int)

X(int) catch

main catch

2

X()

X() catch

~X

f1

f1:catch

f2

f2:catch