c++構造函數異常處理

c++的構造函數中會發生異常處理的情況,這時候其不會跳轉到析構函數了,該異常需要自己來處理。

#include <iostream>

class TestA
{
public:
	TestA()
	{
                //基類中異常
		try
		{
			std::cout << "TestA Contructor" << std::endl;
			throw std::string("testA exception");
		}
		catch (const std::string& exp)
		{
			//std::cout << exp.c_str() << std::endl;
			throw;
		}
		
	}
	~TestA()
	{
		std::cout << "TestA Destructor" << std::endl;
	}
};

class TestB
{
public:
	TestB()
	{
		std::cout << "TestB Constructor" << std::endl;
	}

	~TestB()
	{
		std::cout << "TestB Destructor" << std::endl;
	}
};

class TestC
{
public:
	TestC()
	{
                //異常
		try
		{
			m_a = new TestA();
			m_b = new TestB();
			throw std::string("something trigger a exception");
		}
		catch (const std::string& exp)
		{
			std::cout << exp.c_str() << std::endl;
			Reset();
			throw;
		}

		std::cout << "TestC() Constructor" << std::endl;
	}

	~TestC()
	{
		Reset();
		std::cout << "TestC() Destructor" << std::endl;
	}

	void Reset()
	{
		if (m_a != nullptr)
		{
			delete m_a;
			m_a = nullptr;
		}
		if (m_b != nullptr)
		{
			delete m_b;
			m_b = nullptr;
		}
	}
private:
	TestA* m_a;
	TestB* m_b;
};

int main()
{
	try
	{
		TestC tc;
	}
	catch (...)
	{
		std::cout<<"constructor fail"<< std::endl;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章