004异常中的栈解旋

/*
异常被抛出后,从进入try块起,到异常被抛掷前,这期间在栈上的构造的所有对象,
都会被自动析构。析构的顺序与构造的顺序相反。这一过程称为栈的解旋(unwinding)。
00异常中的栈解旋

	构造函数没有返回类型,无法通过返回值来报告运行状态,所以只通过一种非函数机制的途径,
即异常机制,来解决构造函数的出错问题。
*/
#include<iostream>
using namespace std;
class TestClass
{
public:
	TestClass(int a,int b)
	{
		this->a = a;
		this->b = b;
		cout << "构造函数执行完毕" << endl;
	}
	~TestClass()
	{
		cout << "析构函数执行完毕" << endl;
	}

private:
	int a;
	int b;
};
void MyDivide()
{
	TestClass t1(1,2), t2(3,4);
	cout << "mydivide 要发生异常" << endl;
	/*throw TestClass;*///必须是一个变量实体才可以抛出异常
	throw 1;
}
int main(void)
{
	try
	{
		MyDivide();
	}
	catch (int e)
	{
		cout << "int类型的异常类型" << endl;
	}
	catch (...)
	{
		cout << "其他类型的异常" << endl;
	}
	system("pause");
	return 0;
}
/*
 * 构造函数执行完毕
构造函数执行完毕
mydivide 要发生异常
析构函数执行完毕
析构函数执行完毕
int类型的异常类型
请按任意键继续. . .


 */

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89497572
004