




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、第第 4 章章 異常異常 n北京大學(xué)計(jì)算機(jī)系北京大學(xué)計(jì)算機(jī)系 n代亞非代亞非 2第第4章章 異常異常 n4.1 4.1 異常的概念異常的概念 n4.2 4.2 異常的分類異常的分類 n4.3 4.3 捕獲異常捕獲異常 n4.4 4.4 聲明異常聲明異常 n4.5 4.5 拋出異常拋出異常 n4.6 4.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n4.7 4.7 總結(jié)總結(jié) 34.1 異常的概念異常的概念 n什么是異常什么是異常? 異常實(shí)際上是程序中錯(cuò)誤導(dǎo)致中斷了正異常實(shí)際上是程序中錯(cuò)誤導(dǎo)致中斷了正 常的指令流的一種事件常的指令流的一種事件. n沒(méi)有處理錯(cuò)誤的程序沒(méi)有處理錯(cuò)誤的程序: read-file
2、read-file openTheFile; openTheFile; determine its size; determine its size; allocate that much memory; allocate that much memory; closeTheFile; closeTheFile; 4 4.1 異常的概念異常的概念 n以常規(guī)方法處理錯(cuò)誤以常規(guī)方法處理錯(cuò)誤 openFiles;openFiles; if (theFilesOpen) if (theFilesOpen) determine the lenth of the file; determine the l
3、enth of the file; if (gotTheFileLength) if (gotTheFileLength) allocate that much memory; allocate that much memory; if (gotEnoughMemory) if (gotEnoughMemory) read the file into memory; read the file into memory; if (readFailed) errorCode=-1; if (readFailed) errorCode=-1; else errorCode=-2; else erro
4、rCode=-2; else errorCode=-3; else errorCode=-3; else errorCode=-4 ; else errorCode=-4 ; else errorCode=-5; else errorCode=-5; 54.1 異常的概念異常的概念 n觀察前面的程序你會(huì)發(fā)現(xiàn)大部分精力花在觀察前面的程序你會(huì)發(fā)現(xiàn)大部分精力花在 出錯(cuò)處理上了出錯(cuò)處理上了. n只把能夠想到的錯(cuò)誤考慮到只把能夠想到的錯(cuò)誤考慮到,對(duì)以外的情況對(duì)以外的情況 無(wú)法處理無(wú)法處理 n程序可讀性差程序可讀性差 n出錯(cuò)返回信息量太少出錯(cuò)返回信息量太少 64.1 異常的概念異常的概念 n用異常的形式處
5、理錯(cuò)誤用異常的形式處理錯(cuò)誤 read-File;read-File; try try openTheFile;openTheFile; determine its size; determine its size; allocate that much memory; allocate that much memory; closeTheFile closeTheFile; catch(fileopenFailed) dosomething; catch(fileopenFailed) dosomething; catch(sizeDetermineFailed) dosomething; c
6、atch(sizeDetermineFailed) dosomething; catch(memoryAllocateFailed) dosomething; catch(memoryAllocateFailed) dosomething; catch(readFailed) dosomething; catch(readFailed) dosomething; catch(fileCloseFailed) dosomething; catch(fileCloseFailed) dosomething; 74.1 異常的概念異常的概念 n和傳統(tǒng)的方法比較異常的優(yōu)點(diǎn)和傳統(tǒng)的方法比較異常的優(yōu)點(diǎn):
7、1.把錯(cuò)誤代碼從常規(guī)代碼中分離出來(lái)把錯(cuò)誤代碼從常規(guī)代碼中分離出來(lái) 2. 把錯(cuò)誤傳播給調(diào)把錯(cuò)誤傳播給調(diào) 用堆棧用堆棧 3. 按錯(cuò)誤類型和按錯(cuò)誤類型和 錯(cuò)誤差別分組錯(cuò)誤差別分組 4. 系統(tǒng)提供了對(duì)于一些無(wú)法預(yù)測(cè)的錯(cuò)誤的系統(tǒng)提供了對(duì)于一些無(wú)法預(yù)測(cè)的錯(cuò)誤的 捕獲和處理捕獲和處理 5. 克服了傳統(tǒng)方法的錯(cuò)誤信息有限的問(wèn)題克服了傳統(tǒng)方法的錯(cuò)誤信息有限的問(wèn)題 method1 method2 method3 method4產(chǎn)生異常 傳 遞 處理異常 84.1 異常的概念異常的概念 n. class ExcepTest public void main(String args) int b=0; int a;
8、try a=4/b; catch(ArithmeticException e) System.out.println(“divided by 0”); try URL url=new URL(http:/ catch(MalformedURLEception e) badURL=true; repaint(); 94.2 異常的分類異常的分類 n異常是一個(gè)對(duì)象異常是一個(gè)對(duì)象,它繼承自它繼承自Throwable類類,所有的所有的 Throwable類的子孫類所產(chǎn)生的對(duì)象都是例外類的子孫類所產(chǎn)生的對(duì)象都是例外. nError:由由Java虛擬機(jī)生成并拋出虛擬機(jī)生成并拋出,Java程序不做程序不做
9、處理處理. nRuntime Exception(被被0除等系統(tǒng)錯(cuò)誤除等系統(tǒng)錯(cuò)誤,數(shù)組下數(shù)組下 標(biāo)超范圍標(biāo)超范圍):由系統(tǒng)檢測(cè)由系統(tǒng)檢測(cè), 用戶的用戶的Java 程序可不做程序可不做 處理處理,系統(tǒng)將它們交給缺省的異常處理程序系統(tǒng)將它們交給缺省的異常處理程序. nException(程序中的問(wèn)題程序中的問(wèn)題,可預(yù)知的可預(yù)知的): Java編譯編譯 器要求器要求Java程序必須捕獲或聲明所有的非運(yùn)行程序必須捕獲或聲明所有的非運(yùn)行 時(shí)異常時(shí)異常 nthrow:用戶自己產(chǎn)生異常用戶自己產(chǎn)生異常 10 4.2 異常的分類異常的分類 n.Throwable Error ExceptionExceptio
10、n RuntimeException 缺省的異常缺省的異常 處理程序處理程序 由用戶捕獲或由用戶捕獲或 聲明并處理聲明并處理 不做處理不做處理 用戶自己產(chǎn)生的異常用戶自己產(chǎn)生的異常 要處理要處理 11 4.3 捕獲異常捕獲異常 n捕獲并處理異常捕獲并處理異常 try try / /接受監(jiān)視的程序塊接受監(jiān)視的程序塊, ,在此區(qū)域內(nèi)發(fā)生在此區(qū)域內(nèi)發(fā)生 /的異常的異常, ,由由catchcatch中指定的程序處理中指定的程序處理; ; catchcatch( (要處理的異常種類和標(biāo)識(shí)符要處理的異常種類和標(biāo)識(shí)符) ) / /處理異常處理異常; ; catchcatch( (要處理的異常種類和標(biāo)識(shí)符要處
11、理的異常種類和標(biāo)識(shí)符) ) / /處理異常處理異常; ; 124.3 捕獲異常捕獲異常 n常見(jiàn)的異常常見(jiàn)的異常 nArithmeticExceptionArithmeticException nArrayIndexOutOfBandsExceptionArrayIndexOutOfBandsException nArrayStoreExceptionArrayStoreException nIOExceptionIOException nFileNotFoundExceptionFileNotFoundException nNullPointerExceptionNullPointerExce
12、ption nMalformedURLExceptionMalformedURLException nNumberFormatExceptionNumberFormatException nOutOfMemoryExceptionOutOfMemoryException 如果在使用能夠如果在使用能夠 產(chǎn)生異常的方法產(chǎn)生異常的方法 而沒(méi)有捕獲和處而沒(méi)有捕獲和處 理,將不能通過(guò)理,將不能通過(guò) 編譯編譯 134.3 捕獲異常捕獲異常 n例例:編寫(xiě)編寫(xiě)Java程序程序,包含三種異常包含三種異常 n算術(shù)異常算術(shù)異常, 字符串越界字符串越界,數(shù)組越界數(shù)組越界 n觀察輸出信息觀察輸出信息: n每個(gè)異常對(duì)象可
13、以直接給出信息每個(gè)異常對(duì)象可以直接給出信息 144.3 捕獲異常捕獲異常 class first_exception public static void main(String args) char c; int a,b=0;int array=new int7; String s=Hello; try a=1/b; catch(ArithmeticException ae) System.out.println(“Catch “+ae); try array8=0; catch(ArrayIndexOutOfBoundsException ai) System.out.println(“C
14、atch “+ai); try c=s.charAt(8); catch(StringIndexOutOfBoundsException se) System.out.println(“Catch “+se); 154.3 捕獲異常捕獲異常 l一定會(huì)執(zhí)行的程序塊一定會(huì)執(zhí)行的程序塊-finallyfinally 異常處理的統(tǒng)一出口異常處理的統(tǒng)一出口 try try / /常規(guī)的代碼常規(guī)的代碼; ; catch()catch() / /處理異常處理異常 finally finally / /不論發(fā)生什么異常不論發(fā)生什么異常( (或者不發(fā)生任何異或者不發(fā)生任何異 常常),),都要執(zhí)行的部分都要執(zhí)行的
15、部分; ; 164.3 捕獲異常捕獲異常 nfinally在文件處理時(shí)非常有用在文件處理時(shí)非常有用 ntry n 對(duì)文件進(jìn)行處理的程序?qū)ξ募M(jìn)行處理的程序; ncatch(IOException e) n /對(duì)文件異常進(jìn)行處理對(duì)文件異常進(jìn)行處理; nfinally n 不論是否發(fā)生異常不論是否發(fā)生異常,都關(guān)閉文件都關(guān)閉文件; n 174.4 聲明異常聲明異常 n一個(gè)方法不處理它產(chǎn)生的異常一個(gè)方法不處理它產(chǎn)生的異常, ,而是沿著調(diào)用層次而是沿著調(diào)用層次 向上傳遞向上傳遞, ,由調(diào)用它的方法來(lái)處理這些異常由調(diào)用它的方法來(lái)處理這些異常, ,叫聲叫聲 明異常明異常. . l聲明異常的方法聲明異常的方法
16、 l在產(chǎn)生異常的方法名后面加上要拋出在產(chǎn)生異常的方法名后面加上要拋出(throws)(throws)的的 異常的列表異常的列表 nvoid compute(int x)throws void compute(int x)throws ArithmeticException ArithmeticException nreturnType methodName(parameterlist) returnType methodName(parameterlist) throwsthrows exceptionList exceptionList 184.4 聲明異常聲明異常 例例:若因若因 某種原某
17、種原 因不想因不想 在創(chuàng)建在創(chuàng)建 URL的的 方法中方法中 處理異處理異 常常 public method1() int x; try x=System.in.read(); compute(x); catch(IOException ioe) System.out.println(“read error”); catch(ArithmeticException e) System.out.println(“devided by 0”); public int compute(int x) throws ArithmeticException e) return z=100/x; 194.4
18、聲明異常聲明異常 method1 computer 異常異常 拋出拋出 處理處理 204.4 聲明異常聲明異常 例例:說(shuō)出程序執(zhí)行結(jié)果說(shuō)出程序執(zhí)行結(jié)果 public class exception1 void Proc(int sel) throws ArithmeticException, ArrayIndexOutOfBoundsException System.out.println(“In Situation + sel ); if (sel=0) System.out.println(no Exception caught); return; else if(sel=1) int i
19、Array=new int4; iArray10=3; 21 4.4 聲明異常聲明異常 public static void main(String args) try Proc(0); Proc(1); catch(ArrayIndexOutOfBoundsException e) System.out.println(Catch+e); c:jview throwsExceptionc:jview throwsException In Situation 0In Situation 0 no Exception caughtno Exception caught In Situation
20、1In Situation 1 Catch Catch java.lang.ArrayIndexOutOfBoundsException:10java.lang.ArrayIndexOutOfBoundsException:10 224.5 拋出異常拋出異常 l拋棄異常拋棄異常: 不是出錯(cuò)產(chǎn)生不是出錯(cuò)產(chǎn)生,而是人為地拋出而是人為地拋出 nthrow ThrowableObject; nthrow new ArithmeticException(); n例例:編寫(xiě)程序人為拋出編寫(xiě)程序人為拋出(JavaThrow.prj) ArithmeticException, ArrayIndexOutOfB
21、oundsException StringIndexOutOfBoundsException A methodException Another method throw caught 234.5 拋出異常拋出異常 class JavaThrow public static void main(String args) try throw new ArithmeticException(); catch(ArithmeticException ae) System.out.println(ae); try throw new ArrayIndexOutOfBoundsException();
22、catch(ArrayIndexOutOfBoundsException ai) System.out.println(ai); try throw new StringIndexOutOfBoundsException(); catch(StringIndexOutOfBoundsException si) System.out.println(si); 244.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n不是由不是由Java系統(tǒng)監(jiān)測(cè)到的異常系統(tǒng)監(jiān)測(cè)到的異常(下標(biāo)越界下標(biāo)越界, 被被0-除等除等),而是由用戶自己定義的異常而是由用戶自己定義的異常. n用戶定義的異常同樣要用用戶定義的異常同樣要用tr
23、y-catch捕獲捕獲,但但 必須由用戶自己拋出必須由用戶自己拋出 throw new MyException. n異常是一個(gè)類異常是一個(gè)類,用戶定義的異常必須繼承自用戶定義的異常必須繼承自 Throwable或或Exception類類,建議用建議用 Exception類類. 254.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n形如形如: nclass MyException extends Exception n.; n例例1 :計(jì)算兩個(gè)數(shù)之和計(jì)算兩個(gè)數(shù)之和,當(dāng)任意一個(gè)數(shù)超出范圍時(shí)當(dāng)任意一個(gè)數(shù)超出范圍時(shí), 拋出自己的異常拋出自己的異常 public class NumberRangeExceptio
24、n extends Exception public NumberRangeException(String msg) super(msg); 264.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n. public boolean action(Event evt, Object arg) try int answer = CalcAnswer(); answerStr = String.valueOf(answer); catch (NumberRangeException e) answerStr = e.getMessage(); repaint(); return true; 274.6 創(chuàng)造自
25、己的異常創(chuàng)造自己的異常 n. public int CalcAnswer() throws NumberRangeException int int1, int2; int answer = -1; String str1 = textField1.getText(); String str2 = textField2.getText(); try int1 = Integer.parseInt(str1); int2 = Integer.parseInt(str2); if (int1 20) | (int2 20) NumberRangeException e = new NumberRa
26、ngeException (”Numbers not within the specified range.); throw e; answer = int1 + int2; catch (NumberFormatException e) answerStr = e.toString(); return answer; 284.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n例例2 :在定義銀行類時(shí)在定義銀行類時(shí),若取錢數(shù)大于余額若取錢數(shù)大于余額 則作為異常處理則作為異常處理 (InsufficientFundsException). n思路思路:產(chǎn)生異常的條件是余額少于取額產(chǎn)生異常的條件是余額少于取額,
27、 因因 此是否拋出異常要判斷條件此是否拋出異常要判斷條件 n取錢是取錢是withdrawal方法中定義的動(dòng)作方法中定義的動(dòng)作,因因 此在該方法中產(chǎn)生異常此在該方法中產(chǎn)生異常. n處理異常安排在調(diào)用處理異常安排在調(diào)用withdrawal的時(shí)候的時(shí)候, 因此因此withdrawal方法要聲明異常方法要聲明異常,由上級(jí)由上級(jí) 方法調(diào)用方法調(diào)用 n要定義好自己的異常類要定義好自己的異常類 294.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n. class Bank double balance; public void deposite(double dAmount) if(dAmount0.0) balan
28、ce+=dAmount; public void withdrawal(double dAmount) throws InsufficientFundsException if (balancedAmout) throw new InsufficientFundsException(this,dAmount); balance=balance-dAmount; public void show_balance() System.out.println(The balance is +(int)balance); 304.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 public class Excepti
29、onDemo public static void main(String args) try Bank ba=new Bank(50); ba.withdrawal(100); System.out.println(“Withdrawal successful!”); catch(Exception e) System.out.println(e.toString(); 314.6 創(chuàng)造自己的異常創(chuàng)造自己的異常 n.public class InsufficientFundsException extends Exception private Bank excepbank; private
30、 double excepAmount; InsufficientFundsException(Bank ba, double dAmount) excepbank=ba; excepAmount=dAmount; public String excepMesagge() String str=“The balance”+ excepbank.showBalance()+ “The withdrawal was”+excepAmount; return str; 324.7 小結(jié)小結(jié) 1.1.一般格式一般格式: :正常程序和出錯(cuò)處理分離開(kāi)來(lái)正常程序和出錯(cuò)處理分離開(kāi)來(lái) try Java statement; catche(ExceptionType1 ExceptionObject) Exception1 handling; catche(ExceptionType2 E
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 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ì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 門頭牌匾施工方案
- 物業(yè)管理培訓(xùn)知識(shí)
- 排水溝疏浚施工方案
- 廚師工資協(xié)議合同范例
- 同行之間拿車合同范例
- 公益提供飲品合同范例
- 班級(jí)榮譽(yù)激勵(lì)制度的設(shè)立計(jì)劃
- 促進(jìn)班級(jí)凝聚力的有效措施計(jì)劃
- 職業(yè)網(wǎng)絡(luò)拓展的策略計(jì)劃
- 生產(chǎn)計(jì)劃中的時(shí)間管理策略
- 2024年3月30日事業(yè)單位聯(lián)考A類《職業(yè)能力傾向測(cè)驗(yàn)》試題
- 食堂從業(yè)人員晨午檢制度
- 現(xiàn)代家政導(dǎo)論-課件 2.1家庭的認(rèn)知
- 護(hù)理相關(guān)法律法規(guī)
- 嬰幼兒窒息的預(yù)防與急救
- 【網(wǎng)紅李佳琦直播帶貨營(yíng)銷策略問(wèn)題及對(duì)策13000字(論文)】
- 2024中國(guó)移動(dòng)公司招聘高頻500題難、易錯(cuò)點(diǎn)模擬試題附帶答案詳解
- 江蘇省宿遷市2024年中考數(shù)學(xué)試卷含答案
- 河道綜合治理工程施工組織設(shè)計(jì)(投標(biāo))
- 處方書(shū)寫(xiě)規(guī)范考核試題及答案
- 餐飲配方傳授合同范本
評(píng)論
0/150
提交評(píng)論