第15章异常11摘要.pptVIP

  • 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() 异常机制与函数机制正交(互不干涉),但捕捉的方式是基于类型匹配

文档评论(0)

1亿VIP精品文档

相关文档