ExampleOne.cpp
上传用户:skywee
上传日期:2021-12-09
资源大小:141k
文件大小:1k
- #include <iostream>
- using namespace std;
- class CMyError
- {
- public:
- CMyError()
- {
- ErrCode=0;
- strcpy(ErrInfo,"");
- cout<<"CMyError()"<<endl;
- }
- CMyError(int code, char* pinfo)
- {
- ErrCode = code;
- strcpy(ErrInfo,pinfo);
- cout<<"CMyError()"<<endl;
- }
-
- CMyError(const CMyError &obj)
- {
- ErrCode = obj.ErrCode;
- strcpy(ErrInfo,obj.ErrInfo);
- cout<<"CMyError(const CMyError &obj)"<<endl;
- }
- ~CMyError()
- {
- cout<<"~CMyError()"<<endl;
- }
- virtual void printErrInfo()
- {
- printf("%sn",ErrInfo);
- }
- int ErrCode;
- char ErrInfo[50];
- };
- class CTest
- {
- public:
- int Func(int i)
- {
- try
- {
- if(i<10)
- {
- CMyError e(-2,"不能小于10");
- throw e;
- //throw CMyError(-2, "不能小于10"); //强制类型转换,抛出类类型实例
-
- }
- if(i>20)
- {
- int e;
- e = -1;
- throw -1; //抛出基本类型数据的实例
- }
- }
- catch(CMyError &e)
- {
- e.printErrInfo();
- throw e;
- }
- return i;
- }
- };
- int main(int argc, char* argv[])
- {
- CTest test;
- int iIn;
- cin>>iIn;
- try
- {
- int x=test.Func(iIn);
- cout<<"At the end of try block"<<endl;
- }
- //也可以是
- //catch(CMyError)
- //catch(CMyError &e)
- //如果抛出来的是堆中分配的对象的指针
- //此处也可以接收指针。
- catch(CMyError e)
- {
- cout<<"catch CError object"<<endl;
- int b=2;
- }
- //也可以接收标准数据类型的实例
- catch(int i)
- {
- cout<<"catch int variable:"<<i<<endl;
- }
- return 0;
- }