




版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、C+C+計(jì)算機(jī)語(yǔ)言教學(xué)課件計(jì)算機(jī)語(yǔ)言教學(xué)課件lect11_exception_handlinlect11_exception_handling gObjectives In this chapter, you will learn: what exceptions are and when to use them using try, catch and throw to detect, handle and indicate exceptions respectively what exception class is and how to use it drawback of except
2、ion handling and useful advices10.1 Introduction What are Exceptions and Exception handling? Exceptions indicate problems that occur during a programs execution, and the problems are special that they occur infrequently. Exception handling means resolve exceptions and make the programs robust and fa
3、ult-tolerant( allow a program to continue executing or notify the user of the problem).10.1 Introduction When can we use Exception handling? After distinguishing exceptions from errors. Exception is a special kind of error that the user can not estimate and occurs infrequently. ( Once an error is ha
4、ndled, it is no longer an error. ) For example, when user want to create a file.Exceptions can be these:1. the disk is full 2. do not have permission to create a file. 10.1 Introduction 常見(jiàn)的異常 系統(tǒng)資源不足系統(tǒng)資源不足1)內(nèi)存不足:不可以動(dòng)態(tài)申請(qǐng)內(nèi)存空間2)磁盤(pán)不足:不能創(chuàng)建新的文件 用戶(hù)操作導(dǎo)致運(yùn)算關(guān)系不正確用戶(hù)操作導(dǎo)致運(yùn)算關(guān)系不正確如分母為0、數(shù)學(xué)運(yùn)算溢出、數(shù)組越界、參數(shù)類(lèi)型不能轉(zhuǎn)換等。 異常的特點(diǎn) 偶
5、然性和可預(yù)見(jiàn)性異常的存在和出現(xiàn)可以預(yù)見(jiàn),但不會(huì)總是發(fā)生。 嚴(yán)重性一旦異常產(chǎn)生,程序可能終止或運(yùn)行結(jié)果未知。10.1 Introduction 異常處理方法 不做處理(很多程序都是這樣,但不建議) 發(fā)布錯(cuò)誤信息,然后終止程序的運(yùn)行(在C語(yǔ)言中,往往這樣處理) 適當(dāng)?shù)奶幚懋惓#钩绦蚩梢岳^續(xù)運(yùn)行(最佳的選擇)10.1 Introduction Exception Handling Mechanism(異常處理機(jī)制)1. throwing an exception(拋出異常信號(hào))(拋出異常信號(hào)): Some library software or your code signals(發(fā)出信號(hào)) th
6、at something unusual has happened.2. handling the exception: At some other place in your program you place the code that deals with the exceptional case.10.2 try, catch and throw Keyword try followed by braces( ) Should enclose Statements that might cause exceptions Statements that should be skipped
7、 in case of an exceptionExample:try int* ptr = new int1000000000000000 ;10.2 try, catch and throw Keyword catch( Catch Handlers )Immediately follow by a try block. ( Every try block has one or more catch handlers )Example:try infile.open( 1.txt, ios:in ) ; if ( infile.fail() ) throw -1 ; / /拋出整型對(duì)象,下
8、面會(huì)具體講拋出整型對(duì)象,下面會(huì)具體講catch ( int i ) / / 捕獲捕獲 int int 型的對(duì)象型的對(duì)象 cout “Exception:can not open file” endl ; Exception:can not open file Output Keyword catch( Catch Handlers )Executes if exception parameter type matches the exception thrown in the try block.(catch 按其在try塊后出現(xiàn)的順序被檢查,最先匹配的catch塊將處理該異常)10.2 tr
9、y, catch and throwtry / code to trythrow 1.2 ; / float typefloat typecatch ( int ) / handle exceptions of intcatch ( float ) / handle exceptions of floatcatch ( ExceptionClass ) / handle exceptions of ExceptionClass./* code to execute if no exception or catch handler handled exception*/First match w
10、ins!僅僅通過(guò)僅僅通過(guò)類(lèi)型類(lèi)型而不是通過(guò)而不是通過(guò)值值來(lái)來(lái)匹配的,匹配的,所以catch塊的參數(shù)可以沒(méi)有參數(shù)名稱(chēng),只需要參數(shù)沒(méi)有參數(shù)名稱(chēng),只需要參數(shù)類(lèi)型。類(lèi)型。異常處理的思想函數(shù)g()調(diào)用者 調(diào)用關(guān)系 異常傳播方向 函數(shù)h() 引發(fā)并拋出異常函數(shù)f()捕獲并處理異常10.2 try, catch and throw10.2 try, catch and throw 棧展開(kāi)拋出異常的時(shí)候,將暫停當(dāng)前函數(shù)的執(zhí)行,開(kāi)始查找匹配的catch子句。首先檢查throw本身是否在try 塊內(nèi)部,如果是,檢查與該catch相關(guān)的catch子句,看是否其中之一與拋出對(duì)象相匹配。如果找到匹配的 catch,就處
11、理異常;如果找不到,就退出當(dāng)前函數(shù)(釋放當(dāng)前函數(shù)的內(nèi)在并撤銷(xiāo)局部對(duì)象),并且繼續(xù)在調(diào)用函數(shù)中查找。這個(gè)過(guò)程,稱(chēng)之為棧展開(kāi)(stack unwinding),沿嵌套函數(shù)調(diào)用鏈繼續(xù)向上,直到為異常找到一個(gè)catch子句。只要找到能夠處理異常的catch子句,就進(jìn)入該 catch子句,并在該處理代碼中繼續(xù)執(zhí)行。當(dāng)catch結(jié)束的時(shí)候,在緊接在與該 try 塊相關(guān)的最后一個(gè) catch 子句之后的點(diǎn)繼續(xù)執(zhí)行。10.2 try, catch and throw 異常與析構(gòu)函數(shù) 因異常而退出函數(shù)時(shí),編譯器保證適當(dāng)?shù)爻蜂N(xiāo)局部對(duì)象 如果一個(gè)塊直接分配資源,而且在釋放資源之前發(fā)生異常,在棧展開(kāi)期間將不會(huì)釋放該資
12、源。例如,一個(gè)塊可以通過(guò)調(diào)用 new 動(dòng)態(tài)分配內(nèi)存,如果該塊因異常而退出,編譯器不會(huì)刪除該指針,已分配的內(nèi)在將不會(huì)釋放。 析構(gòu)函數(shù)應(yīng)該從不拋出異常 在為某個(gè)異常進(jìn)行棧展開(kāi)的時(shí)候,析構(gòu)函數(shù)如果又拋出自己的未經(jīng)處理的另一個(gè)異常,將會(huì)導(dǎo)致調(diào)用標(biāo)準(zhǔn)庫(kù)terminate函數(shù)。一般而言,terminate函數(shù)將調(diào)用abort函數(shù),強(qiáng)制從整個(gè)程序非正常退出。 標(biāo)準(zhǔn)庫(kù)類(lèi)型都保證它們的析構(gòu)函數(shù)不會(huì)引發(fā)異常10.2 try, catch and throw Keyword catch( Catch Handlers )Process uncaught and unexpected exceptions.For t
13、hese exceptions that we do not know but have to handle, we can use catch( ) statement to catch all type of operands. try int* ptr = new int1000000000000000 ; catch( int ) /*/ catch( ) / catchcatch all type of operands to to handlehandle unexpected exception cout “unexpected exception occurs endl ; u
14、nexpected exception occursOutput 10.2 try, catch and throw catch異常說(shuō)明符匹配原則異常與 catch 異常說(shuō)明符匹配的規(guī)則比匹配實(shí)參和形參類(lèi)型的規(guī)則更嚴(yán)格,大多數(shù)轉(zhuǎn)換都不允許除下面幾種可能的區(qū)別之外,異常的類(lèi)型與 catch 說(shuō)明符的類(lèi)型必須完全匹配: 允許從非 const 到 const 的轉(zhuǎn)換。也就是說(shuō),非 const 對(duì)象的 throw可以與指定接受 const 引用的 catch 匹配。 允許從派生類(lèi)型型到基類(lèi)類(lèi)型的轉(zhuǎn)換。 將數(shù)組轉(zhuǎn)換為指向數(shù)組類(lèi)型的指針,將函數(shù)轉(zhuǎn)換為指向函數(shù)類(lèi)型的適當(dāng)指針。 在查找匹配 catch 的時(shí)候
15、,不允許其他轉(zhuǎn)換。具體而言,既不允許標(biāo)準(zhǔn)算術(shù)轉(zhuǎn)換(比如不允許int到double的轉(zhuǎn)換),也不允許為類(lèi)類(lèi)型定義的轉(zhuǎn)換。 10.2 try, catch and throw Keyword throwfollowed by an operand representing the type of exception. 1. The throw operand can be of any type throw 表達(dá)式可以拋出任何類(lèi)型的對(duì)象,包括內(nèi)建類(lèi)型(int,float 等)2. If the throw operand is an object, it is called an exceptio
16、n object. (常用) Keyword throwtry throw -1 ; /throw 表達(dá)式很像return 語(yǔ)句,在throw處立即返回 catch( int ) cout exception caught ! endl ; catch( ) / 使用 ()可捕捉任意類(lèi)型的異常,用來(lái)處理未知的異常10.2 try, catch and throw exception caught !Output 10.2 try, catch and throw Exception Specifications在函數(shù)的聲明中列出可能拋出的異常類(lèi)型Example:void fun() throw
17、( int, float, ExceptionClass ) ; /可拋出可拋出int、float、ExceptionClass類(lèi)型的異常類(lèi)型的異常2. 若無(wú)聲明,則可以拋出任何類(lèi)型的異常 void fun()3. 不拋出任何類(lèi)型的異常的聲明如下:void fun() throw() ;表示不拋出異常,如果fun里面的異常沒(méi)有被捕捉到,程序終止?10.2 try, catch and throw Example.Since constructors are not able to return values, we often use exception handling to inform
18、the caller whether the construction is a success or not.class A public: A() infile.open( 1.txt, ios:in ) ; if ( infile.fail() ) throw -1 ; private: ifstream infile ; ;int main() try A a ; catch( int ) cout exception: constructor failed endl ; return 0 ; exception: constructor failedOutput 10.2 try,
19、catch and throw 分層嵌套.當(dāng)在低層的trycatch結(jié)構(gòu)塊中不能匹配到相同類(lèi)型的catch block時(shí),它就會(huì)到上層的trycatch塊中去尋找匹配到正確的catch block異常處理模塊。int main() try /這里是嵌套的trycatch結(jié)構(gòu)塊 try cout “ 準(zhǔn)備拋出一個(gè)double數(shù)據(jù)類(lèi)型的異常. endl; throw 0.5; catch( int& value ) cout 在 catch block 中, int數(shù)據(jù)類(lèi)型處理異常錯(cuò)誤。” endl; catch( double& d_value ) cout 在 catch block 中, d
20、ouble數(shù)據(jù)類(lèi)型處理異常錯(cuò)誤?!?endl; return 0; 10.2 try, catch and throw 分層嵌套.分層嵌套的trycatch塊是可以跨越函數(shù)作用域的。void Func() try /這里實(shí)際上也是嵌套在里層的trycatch結(jié)構(gòu)塊 cout “在 try block 中, 準(zhǔn)備拋出一個(gè)int數(shù)據(jù)類(lèi)型的異常.” endl; /由于這個(gè)trycatch塊中不能找到匹配的catch block,所以 /它會(huì)繼續(xù)查找到調(diào)用這個(gè)函數(shù)的上層函數(shù)的trycatch塊。 throw 1; catch( float& value ) cout 在 catch block 中,
21、int數(shù)據(jù)類(lèi)型處理異常錯(cuò)誤。” endl; int main() try Func(); cout 在 try block 中, 準(zhǔn)備拋出一個(gè)double數(shù)據(jù)類(lèi)型的異常. endl; throw 0.5; catch( double& d_value ) cout “在 catch block 中, double數(shù)據(jù)類(lèi)型處理異常錯(cuò)誤。” endl; catch( int& value ) /這個(gè)例子中,F(xiàn)unc()函數(shù)中拋出的異常會(huì)在此被處理 cout 在 catch block 中, int數(shù)據(jù)類(lèi)型處理異常錯(cuò)誤。” endl; return 0; 10.3 Exception Class D
22、efining an Exception Class Because a throw-statement can throw a value of any type, it is common to define a class whose objects can carry the kind of information you want thrown to the catch-block. A more important reason for a specialized exception class is so you can have a different type to iden
23、tify each possible kind of exceptional situation. An exception class is just a class that happens tobe used as an exception class.10.3 Exception Class Defining an Exception ClassExampleclass ExceptionClasspublic:ExceptionClass() cout“Exception occurs !”endl;int main () try /實(shí)例化類(lèi)ExceptionClass的對(duì)象,并將其
24、拋出 throw ExceptionClass() ; /捕獲類(lèi)ExceptionClass的對(duì)象 catch ( ExceptionClass ) cout “Excepiton caught !” endl ; return 0 ; Exception occurs ! Exception caught !Output 10.3 Exception ClassAnother example/ Class DividByZeroException to be used in exception handling for throwing an exception on a division
25、by zeroclass DivideByZeroException public:DivideByZeroException() :message( “attempted to divide by zero” )const char* what() const return message ; private:const char* message ; ;10.3 Exception Class/ 使用示例try throw DivideByZeroException() ; /調(diào)用類(lèi)DivideByZeroException的構(gòu)造函數(shù),/實(shí)例化類(lèi)DividByZeroException的一
26、個(gè)對(duì)象,并將其拋出catch ( DivideByZeroException ex ) /捕獲類(lèi)DividByZeroException的對(duì)象 cout “Exception occurrs: ” ex.what() endl ; /調(diào)用成員函數(shù) Exception occurs: attempted to divide by zeroOutput 10.3 Exception Class 標(biāo)準(zhǔn)C+異常類(lèi)一個(gè)基類(lèi):一個(gè)基類(lèi):exception(所有異常的基類(lèi))(所有異常的基類(lèi))class exception public: exception() throw() ; exception( co
27、nst exception& rhs ) throw() ; virtual exception() throw() ; virtual const char* what() const throw() ; ;兩個(gè)派生的異常類(lèi)兩個(gè)派生的異常類(lèi)logic_erro 報(bào)告程序的邏輯錯(cuò)誤,可在程序執(zhí)行前被檢測(cè)到報(bào)告程序的邏輯錯(cuò)誤,可在程序執(zhí)行前被檢測(cè)到 runtime_erro 報(bào)告程序運(yùn)行錯(cuò)誤,只有在運(yùn)行時(shí)才能被檢測(cè)到報(bào)告程序運(yùn)行錯(cuò)誤,只有在運(yùn)行時(shí)才能被檢測(cè)到10.3 Exception Class 標(biāo)準(zhǔn)C+異常類(lèi) (需要 #include )邏輯錯(cuò)誤類(lèi)domain_error 報(bào)告違反了前置條件invalid_argument 報(bào)告函數(shù)的參數(shù)無(wú)效out_of_range 報(bào)告參數(shù)越界 運(yùn)行時(shí)錯(cuò)誤類(lèi)bad_alloc報(bào)告存儲(chǔ)分配錯(cuò)誤range_error 報(bào)告計(jì)算中的范圍錯(cuò)誤overflow_error 報(bào)告算術(shù)上溢出underflow_error報(bào)告算術(shù)下溢出10.3 Exception Class 標(biāo)準(zhǔn)C+異常類(lèi) (需要 #include )其類(lèi)層次如下:10.3 Exception Class 標(biāo)準(zhǔn)C+異常類(lèi)
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 高中食品健康知識(shí)專(zhuān)題
- 維護(hù)公共衛(wèi)生營(yíng)造健康環(huán)境
- 2025年脲醛塑料項(xiàng)目申請(qǐng)報(bào)告
- 【呼倫貝爾】2025年內(nèi)蒙古大興安嶺農(nóng)墾(集團(tuán))有限責(zé)任公司招錄人才45人筆試歷年典型考題及考點(diǎn)剖析附帶答案詳解
- 文庫(kù)發(fā)布:護(hù)理課件
- 文庫(kù)發(fā)布:勞動(dòng)法課件
- 腎超聲教學(xué)課件
- 車(chē)床教學(xué)課件
- 歌曲小船教學(xué)課件
- 事故案例071課件
- ge680ct用戶(hù)學(xué)習(xí)-技術(shù)手冊(cè)
- 金蝶云星空V7.7-產(chǎn)品培訓(xùn)-供應(yīng)鏈-庫(kù)存管理
- 簡(jiǎn)約企業(yè)年會(huì)頒獎(jiǎng)晚會(huì)盛典課件
- 小學(xué)英語(yǔ)短語(yǔ)大全62542
- 2023年惠州仲愷城市發(fā)展集團(tuán)有限公司招聘筆試題庫(kù)及答案解析
- 勞動(dòng)防護(hù)用品配備標(biāo)準(zhǔn)(國(guó)標(biāo))
- 國(guó)開(kāi)經(jīng)濟(jì)學(xué)(本)1-14章練習(xí)試題及答案
- 安全生產(chǎn)費(fèi)用提取計(jì)算公式(附計(jì)算模板)
- 赤平投影原理PPT
- 2021年包頭職業(yè)技術(shù)學(xué)院教師招聘試題及答案解析
- DBJ50∕T-342-2019 工程建設(shè)對(duì)既有建(構(gòu))筑物安全影響評(píng)估標(biāo)準(zhǔn)
評(píng)論
0/150
提交評(píng)論