天天看點

構造函數抛出異常

    構造函數抛出異常有兩種:

    (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