异常处理例题.doc_第1页
异常处理例题.doc_第2页
异常处理例题.doc_第3页
异常处理例题.doc_第4页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C+异常处理Eg1:在函数中抛出异常#includeusing namespace std;#define MAX 10int f(int * a,int j) if(j=0&jMAX) return(aj); else throw aaaa;void main() int aMAX=0;trycoutf(a,15)endl;catch(char * s)coutsendl;Eg2:在成员函数种抛出异常:#includeusing namespace std;class StudentDeptpublic: static int Max; StudentDept(char *p) Name=new charMax; strcpy(Name,p); NameMax=0; char p(int i)if(i=0&iMax) return(Namei); else throw cccc;private: char * Name;int StudentDept:Max=20;class Studentpublic: Student(int i,char *j):Dept(j)id=i; StudentDept & q()return(Dept);private: int id; StudentDept Dept;void main() Student a(1,Computer); trycouta.q().p(5); catch(char * m) coutmendl; Eg3#includeusing namespace std;double Div(double, double );void main() try/如果发生异常则只中断try里面的块 cout 7.3/2.0= Div(7.3, 2.0) endl; cout 7.3/0.0= Div(7.3, 0.0) endl; cout 7.3/1.0= Div(7.3, 1.0) endl; catch(double)/try和catch必须相连/参数可以省略但是类型不能省略;建议不要使用简单类型 cout except of deviding zero.n; cout That is ok. n;double Div(double a, double b) if(b=0.0) throw b;/ Throw和catch可以跨函数 return a/b;Eg4:多种异常处理#includeusing namespace std;double Div(double, double );void f()try cout 7.3/2.0= Div(7.3, 2.0) endl; cout 7.3/0.0= Div(7.3, 0.0) endl; cout 7.3/1.0= Div(7.3, 1.0) endl; catch(double)coutdoubleendl;throw a; catch(char)coutcharendl;void g()try f(); catch(char)coutgggggendl;void main() try g(); cout 正确执行完毕. n; catch(int) cout 零做除数错误n; catch(.) cout缺省异常endl;/默认异常处理 cout异常处理完毕endl;double Div(double a, double b) if(b=0.0) throw b; return a/b;Eg5:异常处理和析构#includeusing namespace std;class Apublic:A()A()couterase A object.endl;private:int k;void f()A s;throw 5;coutf() doingendl;void main()tryf();catch(int)coutf() errorendl;/ 的析构函数被调用;异常不处理时不会调用结果:erase A object.f() errorPress any key to continuel Catch对象类型的错误Eg:#includeusing namespace std;class apublic:a(char * net)strcpy(this-net,net);private:char net10;class b:public apublic:b(long card,char * net):a(net)this-card=card;private:long card;class c:public apublic:c(int port,char * net):a(net)this-port=port;private:int port;void net() throw b(1,aaa);void main() trynet();catch(c)cout端口错误;catch(b)cout网卡错误;catch(a)cout网络错误; /注意,基类

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论