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

来源:互联网 发布:阿里云服务器宽带价格 编辑:程序博客网 时间:2024/05/21 14:00
#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 4typedef 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;}

原创粉丝点击