异常类型和异常变量的生命周期

#include <iostream>
using namespace std;

//传统异常处理
int copyfile(char *from, char * to)
{
	if (from==NULL)
	{
		cout<<""<<endl;
		return 1;
	}
	if (to == NULL)
	{
		return 2;
	}
	if (*from == 'a')
	{
		return 3;
	}
	while(*from!='\0')
	{
		*to = *from;
		to++;
		from++;
	}
	*to = '\0';

	return 0;
}

int main00()
{
	char buf1[]="sbcdefghgjkl";
	char buf2[1024];

	int ret = copyfile(buf1,buf2);
	
	switch (ret)
	{
	case 1:
		cout<<"源出错"<<endl;
		break;
	case 2:
		cout<<"目的出错"<<endl;
		break;
	case 3:
		cout<<"过程出错"<<endl;
		break;
	default:
		cout<<"未知异常"<<endl;
		break;
	}
	printf("buf2:\n",buf2);
	system("pause");
	return 0;
}

//throw抛异常

void copyfile2(char *from, char * to)
{
	if (from==NULL)
	{
		throw 1;
	}
	if (to == NULL)
	{
		throw 2;
	}
	if (*from == 'a')
	{
		throw 3;
	}
	while(*from!='\0')
	{
		*to = *from;
		to++;
		from++;
	}
	*to = '\0';
}
//char*异常
void copyfile3(char *from, char * to)
{
	if (from==NULL)
	{
		throw "源异常";
	}
	if (to == NULL)
	{
		throw "目的异常";
	}
	if (*from == 'a')
	{
		throw "过程异常";
	}
	while(*from!='\0')
	{
		*to = *from;
		to++;
		from++;
	}
	*to = '\0';
}

class BadSrc
{};

class Badto{};

class BadPro
{
	public:
		BadPro()
		{
			cout<<"BadPro构造函数"<<endl;
		}
		~BadPro()
		{
			cout<<"BadPro析构函数"<<endl;
		}
		BadPro(const BadPro &obj)
		{
			cout<<"BadPro拷贝构造函数"<<endl;
		}

};

//char*异常
void copyfile4(char *from, char * to)
{
	if (from==NULL)
	{
		throw BadSrc();
	}
	if (to == NULL)
	{
		throw Badto();
	}
	if (*from == 'a')
	{
		throw BadPro();
	}
	if (*from == 'b')
	{
		throw new BadPro();
	}
	while(*from!='\0')
	{
		*to = *from;
		to++;
		from++;
	}
	*to = '\0';
}

int main()
{
	char buf1[]="bbcdefghgjkl";
	char buf2[1024];

	try
	{
		 copyfile4(buf1,buf2);
	}
	catch (int e)
	{
		cout<<"int星异常"<<endl;
	}
	catch (char* p)
	{
		cout<<"char*异常:"<<p<<endl;
	}
	
	catch (BadSrc e)
	{
		cout<<"BadSrc异常:"<<endl;
	}
	catch (Badto e)
	{
		cout<<"Badto异常:"<<endl;
	}
	//结论2:使用引用 会使用throw时的对象 调用一次构造函数 
	catch (BadPro &e)
	{
		cout<<"BadPro  &异常:"<<endl;
	}
	/* //结论1:如果 接收异常使用异常变量 则调用拷贝构造函数
	catch (BadPro e)//是把匿名对象拷贝给e 还是e就是那个匿名对象
	{
		cout<<"BadPro异常:"<<endl;
	}*/
	//结论3:使用指针接收异常 必须手动释放内存 
	//结论4:使用指针接收异常可以同时和元素 引用类型接收异常写在一块  但是引用接收异常不能同时和使用元素写在一块
	catch (BadPro *e)
	{
		delete e;
		cout<<"BadPro  *异常:"<<endl;
	
	}
	catch (...)
	{
		cout<<"未知异常"<<endl;
	}

	printf("buf2:\n",buf2);
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值