2013年3月算法练习(六) C++抛出和捕捉异常

本文介绍了一个使用C++进行多种类型异常处理的例子,包括自定义异常类、基本数据类型异常及枚举类型的异常捕获与处理过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
 #include<string>
using namespace std;
#define TYPE_CLASS 0  //抛出类异常
#define TYPE_INT 1    //抛出整型异常
#define TYPE_ENUM 2
#define TYPE_FLOAT 3
#define TYPE_DOUBLE 4
typedef int TYPE;
enum Week{Monday,Tuesday,Wednessday,Thursday,Friday,Saturday,Sunday};
class MyException{
public:
	MyException(string msg){err_msg=msg;}
	void ShowErrorMsg(){cerr<<err_msg;}  
	~MyException(){}
private:
	string err_msg;
};
void KindOfException(TYPE type) throw(MyException,int,Week,float,double)
{
	switch(type){
	case TYPE_CLASS:
		throw MyException("Exception! Type of Class!\n");
		break;
	case TYPE_INT:
		throw 2011;
		break;
	case TYPE_ENUM:
		throw Monday;
		break;
	case TYPE_FLOAT:
		throw 1.23f;
		break;
	case TYPE_DOUBLE:
		throw 1.23;
		break;
	default:
		break;
	}
}
int main(int argc,char *argv[])
{
	int type;
	cout<<"Input the type(0,1,2,3,4): ";
	cin>>type;
	try{
		KindOfException(type);
	}
	catch(float f){
		cerr<<"float : "<<f<<endl;
	}
	catch(double d)
	{
		cerr<<"double : "<<d<<endl;
	}
	catch(MyException e)
	{
		e.ShowErrorMsg();
	}
	catch(int i)
	{
		cerr<<"Exception ! Type of Int -->"<<i<<endl;
	}
	catch(Week week)
	{

		cerr<<"Exception ! Type of Enum -->";
		if (week==0)
		{
			cerr<<"monday"<<endl;
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值