自己写一个异常类my_own_exception来感知一下异常机制

       在本文中, 我自己来写一个异常类my_own_exception, 主要为了感知一下C++异常机制, 看代码:

 

#include <iostream>
using namespace std;

class my_own_exception
{
private:
	char szMsg[1024];

public:
	my_own_exception(const char *p)
	{
		memset(szMsg, 0, sizeof(szMsg));
		strncpy(szMsg, p, sizeof(szMsg) - 1);
	}

	const char *what()
	{
		return szMsg;
	}
};

int main()
{
	try
	{
		int x = 1;
		int y = 0;
		if(0 == y)
		{
			throw my_own_exception("error!!!");
		}
	}
	catch(my_own_exception &e)
	{
		cout << e.what() << endl;
	}

	return 0;
}

        结果:error!!!
 

 

       但在玩这代码的时候, 我发现了一个奇怪的问题:

 

#include <iostream>
using namespace std;

class my_own_exception
{
public:
	~my_own_exception()
	{
		cout << "destructor" << endl;
	}
};

int main()
{
	try
	{
		throw my_own_exception();
	}
	catch(...)
	{

	}

	return 0;
}

 

       结果是:

destructor
destructor

 

       再看程序:

 

#include <iostream>
using namespace std;

class my_own_exception
{
public:
	~my_own_exception()
	{
		cout << this << endl;
		cout << "destructor" << endl;
	}
};

int main()
{
	try
	{
		throw my_own_exception();
	}
	catch(...)
	{

	}

	return 0;
}

 

       结果是:

0013FF68
destructor
0013FF6C
destructor

 

       继续看程序:

 

#include <iostream>
using namespace std;

class my_own_exception
{
public:
	virtual ~my_own_exception()
	{
		cout << this << endl;
		cout << "destructor" << endl;
	}
};

int main()
{
	try
	{
		throw my_own_exception();
	}
	catch(...)
	{

	}

	return 0;
}

 

       结果是:

0013FF6C
destructor

 

       2. 3 4程序的具体原因, 我还没有太弄懂, 等以后弄懂了, 再回来完善本文。 有清楚的朋友, 也请不吝赐教。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值