- 5
- 0
- 约1.31万字
- 约 63页
- 2016-10-31 发布于湖北
- 举报
第15章异常11摘要.ppt
int main() { //ff(); try{ int j=0; double d=2.3; char str[20]=Hello; string str1=String; coutPlease input a exception number: ; int a; cina; switch(a){ case 1: throw d; case 2: throw j; case 3: throw str; case 4: throw A(); case 5: throw B(); case 6: str1+=6; throw str1; case 7: str1+=7; throw (string *)str1; case 8: throw(new CExp(CExp)); default: coutNo throws here.\n; } }catch(int){ coutint exception.\n; }catch(double){ coutdouble exception.\n; }catch(char* ss){ coutchar* exception. ssendl; }catch(A){ coutclass A exception.\n; }catch(B){ coutclass B exception.\n; }catch(string str){ coutstr.c_str()endl; }catch(string* str11) { coutddffendl; }catch(CExp *e) { coute-nameendl; delete e; } coutThats ok.\n; } * * * * * * * * * * 在这种简单应用的场合,没必要使用异常,可以用下列代码替代: if(!in){ cout“Error Opening File”argv[1]“\n”; return 1;} for(string s; getline(in, s); coutsendl );} 15.2.3 跨越函数的异常处理 在f1502.cpp中,是在出现错误时,从出现错误处到处理错误处,沿着函数调用的足迹,一步步往上返回,几经周折后,出错信息早已丢失,剩下的只有出错状态,程序f1504.cpp改写为异常处理方式处理,就可以实现跨函数的大跳转了: f1504.cpp #includefstream #includeiostream using namespace std; void procFileName(string s); void procOpenMode(string s); void openIn(string s); void openOut(string s); int main(){ procFileName(iabc); procFileName(oabc);} void procFileName(string s){ try{ for(char c=0; c=9; c++) procOpenMode(s + c+.txt);} catch(string s){ couterror opening s not existed.\n;}} void procOpenMode(string s){ if(s[0]==i) openIn(s); else openOut(s);} void openIn(string s){ ifstream in(s.c_str()); if(!in) throw s+ inFile; for(string line; getline(in, line); coutline\n);} void openOut(string s){ fstream out(s.c_str(),ios::in|ios::out|ios::ate); if(!out) throw s+string( outFile); outs+ outFile is ok.\n; couts+ is here.\n;} 15.3.1 类型匹配 try语句中,涉及到类的,本质上都是函数调用。 throw A() 异常机制与函数机制正交(互不干涉),但捕捉的方式是基于类型匹配
您可能关注的文档
最近下载
- JBT 7368-2015 工业过程控制系统用阀门定位器.docx VIP
- TCECS870-2021 绿色建筑被动式设计导则.pdf VIP
- 2025-2026学年小学数学六年级上册苏教版(2024)教学设计合集.docx
- 整合营销传播——品牌传播的策划、创意与管理(第2版)程宇宁-第十二章 公共关系与公益活动策划与实施.ppt VIP
- 初一语文七年级上下册古诗词硬笔描红字帖.pdf VIP
- 案场礼宾培训课件.ppt VIP
- 2025年MBA全国联考管理试题含答案 .pdf VIP
- 整合营销传播——品牌传播的策划、创意与管理(程宇宁)第四章 识别和判断目标消费者.ppt VIP
- 英语中考专题练习首字母填空有答案.doc VIP
- 第四章水驱曲线..ppt VIP
原创力文档

文档评论(0)