面向?qū)ο蟪绦蛟O(shè)計08-1.異常處理_第1頁
面向?qū)ο蟪绦蛟O(shè)計08-1.異常處理_第2頁
面向?qū)ο蟪绦蛟O(shè)計08-1.異常處理_第3頁
面向?qū)ο蟪绦蛟O(shè)計08-1.異常處理_第4頁
面向?qū)ο蟪绦蛟O(shè)計08-1.異常處理_第5頁
已閱讀5頁,還剩23頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、八、異常處理八、異常處理n程序中潛在的異常問題程序中潛在的異常問題n異常處理機制異常處理機制nC+C+中的異常處理中的異常處理n標(biāo)準(zhǔn)異常標(biāo)準(zhǔn)異常n使用異常處理應(yīng)注意的幾個問題使用異常處理應(yīng)注意的幾個問題【例】求解一元二次方程【例】求解一元二次方程ax2+bx+c=0ax2+bx+c=0#include#include#include#includeusing namespace std;using namespace std;int main()int main() float a,b,c;float a,b,c;double x1,x2;double x1,x2;coutcoutabc;ci

2、nabc;x1=(-b+sqrt(x1=(-b+sqrt(b b* *b-4b-4* *a a* *c c)/2)/2* *a;a;x2=(-b-sqrt(x2=(-b-sqrt(b b* *b-4b-4* *a a* *c c)/2)/2* *a;a;coutcout方程的實根是方程的實根是: x1=x1 x2=x2endl;: x1=x1 x2=x2endl;return 0;return 0; n問題的分析問題的分析n能夠正常運行的程序可能存在很多潛在隱患。程序運行時可能夠正常運行的程序可能存在很多潛在隱患。程序運行時可以檢測到的一些非正常情況稱為異常(以檢測到的一些非正常情況稱為異常(

3、ExceptionException)。如除數(shù))。如除數(shù)為為0 0,數(shù)組越界訪問,內(nèi)存空間不夠,輸入輸出不正常(文件,數(shù)組越界訪問,內(nèi)存空間不夠,輸入輸出不正常(文件找不到、輸入數(shù)據(jù)類型錯等)等等。找不到、輸入數(shù)據(jù)類型錯等)等等。n異常是程序錯誤一種形式。異常是程序錯誤一種形式。n程序中的錯誤按性質(zhì)可分為:程序中的錯誤按性質(zhì)可分為:n語法錯誤語法錯誤( (關(guān)鍵字拼寫錯、標(biāo)識符未定義、語句不完整等關(guān)鍵字拼寫錯、標(biāo)識符未定義、語句不完整等) )n邏輯錯誤邏輯錯誤( (算法設(shè)計有誤導(dǎo)致得不到期望結(jié)果算法設(shè)計有誤導(dǎo)致得不到期望結(jié)果) )n異常異常( (出現(xiàn)是不可避免的,必須加以控制和處理出現(xiàn)是不可避免

4、的,必須加以控制和處理) )n需要進行異常處理,從而減少異常對程序運行的需要進行異常處理,從而減少異常對程序運行的影響,提高程序的容錯性。影響,提高程序的容錯性。n異常處理機制提供了系統(tǒng)層次上的標(biāo)準(zhǔn)設(shè)施,其異常處理機制提供了系統(tǒng)層次上的標(biāo)準(zhǔn)設(shè)施,其主要任務(wù)有以下幾點:主要任務(wù)有以下幾點:n能夠在異常發(fā)生時,在執(zhí)出點拋出異常,并將有關(guān)異常的信能夠在異常發(fā)生時,在執(zhí)出點拋出異常,并將有關(guān)異常的信息以類型的形式傳遞到異常處理模塊;息以類型的形式傳遞到異常處理模塊;n建立模塊之間的異常通信機制,特別是在多層模塊之間實現(xiàn)建立模塊之間的異常通信機制,特別是在多層模塊之間實現(xiàn)異常有序的傳遞,保證拋出的每個異

5、常都能被適當(dāng)?shù)漠惓L幃惓S行虻膫鬟f,保證拋出的每個異常都能被適當(dāng)?shù)漠惓L幚砟K捕獲。理模塊捕獲。n保證異常發(fā)生時能自動釋放異常模塊所占用的系統(tǒng)資源。保證異常發(fā)生時能自動釋放異常模塊所占用的系統(tǒng)資源。n對于不執(zhí)行異常處理的代碼沒有任何額外的運行負擔(dān)。對于不執(zhí)行異常處理的代碼沒有任何額外的運行負擔(dān)。n將異常處理代碼從普通代碼中分離出來。將異常處理代碼從普通代碼中分離出來。n 異常的拋出、檢測和捕獲異常的拋出、檢測和捕獲n 異常在多層模塊間的傳遞異常在多層模塊間的傳遞n 異常接口聲明異常接口聲明n 異常處理中析構(gòu)函數(shù)的調(diào)用異常處理中析構(gòu)函數(shù)的調(diào)用n 異常類的層次結(jié)構(gòu)異常類的層次結(jié)構(gòu)n異常拋出、檢測和

6、捕獲的語法定義如下:異常拋出、檢測和捕獲的語法定義如下:異常拋出:異常拋出:throw throw 表達式;表達式;異常的檢測和捕獲由異常的檢測和捕獲由try-catchtry-catch結(jié)構(gòu)實現(xiàn):結(jié)構(gòu)實現(xiàn):trytry 被檢測可能會發(fā)生異常的語句被檢測可能會發(fā)生異常的語句 catch(catch(異常的類型異常的類型) ) 異常處理的語句異常處理的語句 int main() int main() float a,b,c;float a,b,c;double x1,x2;double x1,x2;coutcoutabc;cinabc;trytry if(0 = a) if(0 = a) thr

7、ow athrow a;/ b;/ b并無意義,代表并無意義,代表floatfloat型即可型即可if(bif(b* *b-4b-4* *a a* *c)0) c)0) throw 1.0throw 1.0; ;x1=(-b+sqrt(bx1=(-b+sqrt(b* *b-4b-4* *a a* *c)/2c)/2* *b;b;x2=(-b-sqrt(bx2=(-b-sqrt(b* *b-4b-4* *a a* *c)/2c)/2* *b;b;coutcout方程的實根是方程的實根是: x1=x1 x2=x2endl;: x1=x1 x2=x2endl; catch(float)catch(f

8、loat)/捕獲捕獲floatfloat類型的異常類型的異常 cout cout系數(shù)系數(shù)b b不能為不能為0 0,方程無解,方程無解!endl; !endl; catch(double)catch(double)/捕獲捕獲doubledouble類型的異常類型的異常 cout cout開方為負值,方程無解開方為負值,方程無解!endl; !endl; coutcout程序結(jié)束程序結(jié)束!endl;!endl;return 0;return 0; 【例】函數(shù)嵌套情況下的異常處理【例】函數(shù)嵌套情況下的異常處理typedef struct zero/typedef struct zero/聲明除數(shù)為零

9、異常類型聲明除數(shù)為零異常類型string s;ZERO;string s;ZERO;typedef struct negative/typedef struct negative/聲明開方值為負異常類型聲明開方值為負異常類型string s;NEGATIVE;string s;NEGATIVE;fun2(int a,int b,int c)/fun2(int a,int b,int c)/拋出異常的函數(shù)拋出異常的函數(shù) ZERO s1;NEGATIVE s2;ZERO s1;NEGATIVE s2; s1.s= s1.s=除數(shù)為零除數(shù)為零;s2.s=;s2.s=開方值為負數(shù)開方值為負數(shù);if(0

10、 = a) if(0 = a) throw s1throw s1; ;if(bif(b* *b-4b-4* *a a* *c)0) c)0) throw s2throw s2; ;return sqrt(breturn sqrt(b* *b-4b-4* *a a* *c);c); fun1(int a,int b,int c) /fun1(int a,int b,int c) /捕獲異常并重新拋出異常捕獲異常并重新拋出異常trytry return (-b+fun2(a,b,c)/(2 return (-b+fun2(a,b,c)/(2* *a); a); catch(ZERO)catch(Z

11、ERO) throwthrow;/;/重新拋出異常重新拋出異常 int main() int main() float a,b,c;float a,b,c;coutcoutabc;cinabc;trytry cout cout方程的一個實根是方程的一個實根是: x1=fun1(a,b,c)endl; : x1=fun1(a,b,c)endl; catch(ZERO S1) /catch(ZERO S1) /捕獲除數(shù)為零異常捕獲除數(shù)為零異常, ,并處理異常并處理異常 coutS1.s coutS1.s,方程無解,方程無解!endl; !endl; catch(NEGATIVE S2)/ catc

12、h(NEGATIVE S2)/ 捕獲開方值為負數(shù)異常捕獲開方值為負數(shù)異常, ,并處理異常并處理異常 coutS2.s coutS2.s,方程無解,方程無解!endl; !endl; coutcout程序結(jié)束程序結(jié)束!endl;!endl;return 0;return 0; 異常處理開始本模塊中是否有try-catch結(jié)構(gòu)進行異常處理是否有匹配的catch子句catch子句是否重新拋出異常異常處理結(jié)束是否有上級模塊(調(diào)用棧是否為空)是否有匹配的catch子句進行異常正理終止程序運行否是是否是是否是否否n在使用可能拋出異常的函數(shù)時,可能需要知道該在使用可能拋出異常的函數(shù)時,可能需要知道該函數(shù)拋出

13、的異常類型,函數(shù)拋出的異常類型,C+C+專門提供了異常接口專門提供了異常接口聲明,也稱為異常規(guī)范。聲明,也稱為異常規(guī)范。n其語法形式如下:其語法形式如下:函數(shù)類型函數(shù)類型 函數(shù)名函數(shù)名( (函數(shù)參數(shù)表函數(shù)參數(shù)表) ) throw (throw (異常類型表異常類型表) )n其中異常類型表包括該函數(shù)中所有可以拋出的異常類型,其中異常類型表包括該函數(shù)中所有可以拋出的異常類型,異常類型之間用逗號分開。異常類型之間用逗號分開。n異常接口聲明是函數(shù)接口的一部分,是函數(shù)使用者和函數(shù)異常接口聲明是函數(shù)接口的一部分,是函數(shù)使用者和函數(shù)之間的協(xié)議。之間的協(xié)議。#include #include using na

14、mespace std;using namespace std;void Fun( void );void Fun( void );class intArray class intArray public:public:intArray(int n) intArray(int n) p = new int n ; p = new int n ; coutcout構(gòu)造構(gòu)造intArrayintArray,分配具有,分配具有”n“n“個元素的數(shù)組。個元素的數(shù)組。 endl; endl; intArray() intArray() delete p;delete p;cout cout 析構(gòu)析構(gòu)in

15、tArrayintArray,釋放資源。,釋放資源。 endl; endl; private:private:int int * *p;p;void Fun() void Fun() intArray ia(10);intArray ia(10);cout cout 在在Fun()Fun()中拋擲整型異常。中拋擲整型異常。 endl; endl; throw 1; throw 1; int main() int main() try try cout cout 在主函數(shù)的在主函數(shù)的trytry塊中調(diào)用函數(shù)塊中調(diào)用函數(shù)Fun()Fun()。 endl; endl;Fun();Fun(); cat

16、ch( int ) catch( int ) cout cout 在主函數(shù)在主函數(shù)catchcatch子句捕獲到整型異常子句捕獲到整型異常, ;, ;cout cout 并進行異常處理。并進行異常處理。 endl; endl; cout cout 程序結(jié)束程序結(jié)束! endl;! endl;return 0;return 0; #include #include #include #include using namespace std;using namespace std;class Excp /class Excp /聲明異常基類聲明異?;?public:public:static v

17、oid print( string msg )/ static void print( string msg )/ 打印錯誤信息打印錯誤信息 coutmsgendl; coutmsgendl; ;class pushOnFull : public Excp /class pushOnFull : public Excp /聲明棧滿異常類聲明棧滿異常類public:public:pushOnFull( int i ) : tempvalue( i ) pushOnFull( int i ) : tempvalue( i ) int getTempValue() return tempvalue;

18、 int getTempValue() return tempvalue; private:private:int tempvalue; /int tempvalue; /存放異常發(fā)生時沒有壓棧的值存放異常發(fā)生時沒有壓棧的值;class popOnEmpty : public Excp ;/class popOnEmpty : public Excp ;/聲明??债惓n惵暶鳁?债惓n?class newError : public Excp ; /class newError : public Excp ; /聲明動態(tài)分配內(nèi)存異常類聲明動態(tài)分配內(nèi)存異常類 class otherError :

19、public Excp ;/class otherError : public Excp ;/聲明其它異常類聲明其它異常類 class Stack class Stack public:public:Stack( int capacity=10 ) throw (newError);/Stack( int capacity=10 ) throw (newError);/建立一空棧建立一空棧Stack()delete elements;/Stack()delete elements;/析構(gòu)函數(shù),釋放數(shù)組資源析構(gòu)函數(shù),釋放數(shù)組資源void push( int value ) throw (push

20、OnFull);/void push( int value ) throw (pushOnFull);/壓棧壓棧void pop(int &top_value) throw (popOnEmpty);/void pop(int &top_value) throw (popOnEmpty);/出棧出棧bool isfull()return top maxsize? false : true;bool isfull()return top maxsize? false : true;bool isempty()return top ? false : true;bool isemp

21、ty()return top ? false : true;int size() return top; int size() return top; void display();void display();private:private:int top;/int top;/棧頂指針棧頂指針int int * * elements;/ elements;/存放棧中元素的棧數(shù)組存放棧中元素的棧數(shù)組int maxsize;/int maxsize;/??扇菁{元素的個數(shù)棧可容納元素的個數(shù);Stack:Stack( int capacity):top(0), maxsize(capacity) S

22、tack:Stack( int capacity):top(0), maxsize(capacity) elements = new intcapacity; /elements = new intcapacity; /動態(tài)創(chuàng)建棧數(shù)組動態(tài)創(chuàng)建棧數(shù)組if(0=elements) throw newError();/if(0=elements) throw newError();/如果分配失敗拋出異常如果分配失敗拋出異常 void Stack:pop( int &top_value ) void Stack:pop( int &top_value ) if ( isempty()

23、) throw popOnEmpty();/if ( isempty() ) throw popOnEmpty();/???,則拋出異常棧空,則拋出異常top_value = elements -top ;top_value = elements -top ; void Stack:push( int value ) void Stack:push( int value ) if ( isfull() )if ( isfull() )throw pushOnFull(value);/throw pushOnFull(value);/棧滿拋出異常棧滿拋出異常elementstop+ = value

24、;elementstop+ = value; void Stack:display() void Stack:display() if ( !size() )if ( !size() ) cout cout 棧中已沒有元素!棧中已沒有元素!n; return; n; return; cout (cout (棧中有棧中有 size() size() 個元素個元素)( bottom: ;)( bottom: ;for ( int i = 0; i top; +i )for ( int i = 0; i top; +i )cout elementsi ;cout elementsi ;cout :t

25、op )n;cout :top )n; int main() int main() int i,n,count;int i,n,count;try try cout cout n;cin n;Stack myStack(n);Stack myStack(n);cout cout n;cin n;for ( i = 1; i = n; count=+i )for ( i = 1; i = n; count=+i )myStack.push( i );myStack.push( i );myStack.display();myStack.display();cout cout n;cin n;fo

26、r ( i = 1; i = n; count=i+ )for ( i = 1; i = n; count=i+ ) int x; int x;myStack.pop( x );myStack.pop( x ); cout cout 已出棧已出棧countcount個元素個元素!n;!n; catch(pushOnFull e) catch(pushOnFull e) e.print(e.print(棧已滿!棧已滿!););cout cout 棧中有棧中有count-1count-1個元素個元素,;,;coutcout值為值為e.getTempValue()e.getTempValue()的元

27、素沒有壓入棧的元素沒有壓入棧n;n; catch(newError)catch(newError) newError:print( newError:print(給棧分配空間時出錯!給棧分配空間時出錯!); ); catch(popOnEmpty) catch(popOnEmpty) cout cout 已出棧已出棧countcount個元素個元素,;,;popOnEmpty:print(popOnEmpty:print(棧已空!棧已空!);); catch(Excp)catch(Excp) Excp:print( Excp:print(程序其它異常在此處理!程序其它異常在此處理!); );

28、return 0;return 0; nC+C+標(biāo)準(zhǔn)庫提供的標(biāo)準(zhǔn)異常類的層次結(jié)構(gòu)標(biāo)準(zhǔn)庫提供的標(biāo)準(zhǔn)異常類的層次結(jié)構(gòu) exceptionlogic_errorruntime_errorbad_allocbad_exceptionbad_castbad_typeidios_base:failurelength_errordomain_errorout_of_rangeinvalid:argumentrange_erroroverflow_errorunderflow:errorn標(biāo)準(zhǔn)異常的根是標(biāo)準(zhǔn)異常的根是exceptionexception類類 ,其聲明如下:,其聲明如下:namespace st

29、d /exception namespace std /exception 類在命名空間類在命名空間std std 中中class exception class exception public:public:exception() throw();/exception() throw();/缺省構(gòu)造函數(shù)缺省構(gòu)造函數(shù)exception( const exception & ) throw();/exception( const exception & ) throw();/拷貝構(gòu)造函數(shù)拷貝構(gòu)造函數(shù)exception& operator=( const exceptio

30、n& ) throw(); exception& operator=( const exception& ) throw(); virtual exception() throw();/virtual exception() throw();/析構(gòu)函數(shù)析構(gòu)函數(shù)/ what()/ what()返回一個字符串,用于異常的文本描述。返回一個字符串,用于異常的文本描述。 virtual const charvirtual const char* * what() const throw(); what() const throw(); n標(biāo)準(zhǔn)異常的使用標(biāo)準(zhǔn)異常的使用#inclu

31、de/#include/標(biāo)準(zhǔn)異常的頭文件標(biāo)準(zhǔn)異常的頭文件#include#include#include#includeusing namespace std;using namespace std;class Array class Array public:public:Array(const char Array(const char * *source, int sz) source, int sz) size = sz; size = sz; ca = new charsize; ca = new charsize; for ( int i = 0; i size; +i ) for

32、 ( int i = 0; i size; +i )if ( !source )if ( !source ) cai = 0; cai = 0;elseelse cai = sourcei; cai = sourcei; char &operator( int i ) const char &operator( int i ) const if ( i = size ) if ( i = size ) string es =string es =數(shù)組越界!數(shù)組越界!;throw out_of_range( es );throw out_of_range( es ); / /將將

33、eses字符串傳入對象字符串傳入對象 return cai; return cai; private:private:int size;int size;char char * *ca;ca;int main() int main() try try char ca = A,B,C,D,E,F; char ca = A,B,C,D,E,F; Array CA( ca, sizeof(ca)/sizeof(char) ); Array CA( ca, sizeof(ca)/sizeof(char) ); CA5=X;/ CA5=X;/正常訪問字符數(shù)組類正常訪問字符數(shù)組類 CA6=G;/CA6=G

34、;/越界訪問數(shù)組類將引發(fā)異常越界訪問數(shù)組類將引發(fā)異常 return 0;return 0; catch ( catch ( const out_of_range &excpconst out_of_range &excp ) ) cout excp.what()endl;/ cout excp.what()endl;/獲取異常信息獲取異常信息 return -1;return -1; n在在C+C+的程序設(shè)計中,異常處理應(yīng)主要用于獨立的程序設(shè)計中,異常處理應(yīng)主要用于獨立開發(fā)的程序模塊之間的異常通信。開發(fā)的程序模塊之間的異常通信。n異常處理機制的使用會影響程序的執(zhí)行效率。因此異常處理機制的使用會影響程序的執(zhí)行效率。因此,即使,即使C+C+支持異常處理,在程序設(shè)計時也應(yīng)該具體支持異常處理,在程序設(shè)計時也應(yīng)該具體情況具體分析。在設(shè)計一個模塊時,如果該模

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論