付費(fèi)下載
下載本文檔
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
第8 Java異常處2122323332try-catch-finally捕獲異常方4353throw和throws拋出異434253不管使用哪種語言進(jìn)行程序設(shè)計(jì),都會(huì)產(chǎn)生各種各樣的錯(cuò)誤。Java為提供了強(qiáng)大的異常處2122323332try-catch-finally捕獲異常方4353throw和throws拋出異434253實(shí)例 那么將拋出ArithmeticException異常,但是浮點(diǎn)數(shù)被0除,將不算數(shù)異常,這與數(shù)學(xué)中不同。本實(shí)8.1所示。8.1EclipseArithExcepArithExcep.java文件。在該類的主方法中演示出現(xiàn)算數(shù)異常的情況??梢苑謩e編寫浮點(diǎn)數(shù)和整數(shù)除以0時(shí)的代碼情況。代碼如下所示:publicclassArithExcep publicpublicstaticvoidmain(String[]args){doublea=1.0;for(inti=10;i>0;i--){System.out.print(""+(i/(i-1)));if(i%5==0)}一個(gè)浮點(diǎn)數(shù)//0-10//5}}Java引入了先進(jìn)的異常處理機(jī)制。它對異常的處理是面象的,也就是將異常當(dāng)作對象來處理。throw語句產(chǎn)生的異常。系統(tǒng)會(huì)根據(jù)異常的類型,查找相應(yīng)的處理方法。發(fā)生異發(fā)生異程序運(yùn)交由Java默認(rèn)的異常處理機(jī)來處8.2實(shí)例 數(shù)組下標(biāo)越界異常即ArrayIndexOutOfBoundsException,當(dāng)?shù)臄?shù)組元素的下標(biāo)值大于數(shù)組的最界異常(ArrayIndexOutOfBoundsException)8.3所示。8.3publicclassArrayExceppublicstaticvoidmain(String[]args){inta[]=newint[5];for(inti=0;i<10;i++){a[i]=i+1;System.out.print(""+}}}5publicclassArrayExceppublicstaticvoidmain(String[]args){inta[]=newint[5];for(inti=0;i<10;i++){a[i]=i+1;System.out.print(""+}}}5//09的for//如果要遍歷數(shù)組中的全部元素,使用foreach循環(huán),它可以避免數(shù)組的下標(biāo)越界。如果要使用ArrayList類也可以避免這些問題。實(shí)例 圖8.4所示。8.4publicclassArrayStoreExceppublicstaticvoidmain(String[]args){Objectobj[]=newString[5];for(inti=0;i<obj.length;i++){obj[i]=newInteger(i);System.out.print(""+obj[i]);}}}//創(chuàng)建一個(gè)數(shù)組類型為Object//intobjpublicclassArrayStoreExceppublicstaticvoidmain(String[]args){Objectobj[]=newString[5];for(inti=0;i<obj.length;i++){obj[i]=newInteger(i);System.out.print(""+obj[i]);}}}//創(chuàng)建一個(gè)數(shù)組類型為Object//intobjArrayStoreException(數(shù)組異常),當(dāng)向數(shù)組中存放非數(shù)組類型對象時(shí)拋出實(shí)例 這兩個(gè)類型不兼容而無法完成轉(zhuǎn)換時(shí)會(huì)出現(xiàn)ClassCastException異常。本實(shí)例將演示強(qiáng)制類型轉(zhuǎn)換異(ClassCastException)8.58.5publicclassClassCastExceppublicstaticvoidmain(String[]args){Objectx=newInteger(0);System.out.println((String)x);}}//創(chuàng)建一個(gè)publicclassClassCastExceppublicstaticvoidmain(String[]args){Objectx=newInteger(0);System.out.println((String)x);}}//創(chuàng)建一個(gè)Integer//將x轉(zhuǎn)換為一個(gè)StringClassCastException異常。實(shí)例 使用了一個(gè)被設(shè)為null對象時(shí),就會(huì)該異常。本實(shí)例將演示空指針異常(NullPointerException)的8.6所示。8.6publicclassNullPointExcep{staticTesttest;publicstaticvoidmain(String[]args){}}classTest//null對象//使用test調(diào)用talk()在Eclipse中新建項(xiàng)目NullPointExcep,并在其中創(chuàng)建一個(gè)NullPointExcep.java文件。在程序中使publicclassNullPointExcep{staticTesttest;publicstaticvoidmain(String[]args){}}classTest//null對象//使用test調(diào)用talk()publicStringtalk(){publicStringtalk(){return"thisisaboy";}//}初始化的對象或者是不存在的對象。這個(gè)錯(cuò)誤經(jīng)常出現(xiàn)在創(chuàng)建、調(diào)用數(shù)組這些操作中,如初始化,或者創(chuàng)建時(shí)的路徑錯(cuò)誤等等實(shí)例 NumberFormatException。本實(shí)例將演示數(shù)字格式轉(zhuǎn)換異常(NumberFormatException)8.7所示。8.7publicclassNumFormatExcep{privateStringname;privateStringpassword;publicStringgetName()//創(chuàng)建一個(gè)String//創(chuàng)建一個(gè)String//get和set在Eclipse中新建項(xiàng)目NumFormatExceppublicclassNumFormatExcep{privateStringname;privateStringpassword;publicStringgetName()//創(chuàng)建一個(gè)String//創(chuàng)建一個(gè)String//get和setreturnreturn}publicvoidsetName(Stringname){=name;}publicStringgetPassword(){returnpassword;}publicvoidsetPassword(Stringpassword){this.password=password;}publicstaticvoidmain(String[]args){NumFormatExcepr7=newNumFormatExcep();Stringname=//intpassword=newInteger(r7.getPassword()).intValue();//將String類型強(qiáng)制轉(zhuǎn)換為intSystem.out.println("用戶名為"+name+ 為"+}}實(shí)例 StringIndexOutOfBoundsException,當(dāng)對變量所賦值大于其初始化規(guī)定的大小時(shí)發(fā)生,也就是字符串長度大于charAt()方定的長度時(shí)發(fā)生。本實(shí)例將演示出現(xiàn)字符串索引越界異常(StringIndexOutOfBoundsException)8.8所示。8.8在Eclipse中新建項(xiàng)目SIOOBExcep,并在其中創(chuàng)建一個(gè)SIOOBExcep.java文件。在該類的主方法中創(chuàng)建一個(gè)字符串str,然后一個(gè)長度為30的字符集ch,將str的值賦給ch。代碼如下所示:publicpublicclassSIOOBExceppublicstaticvoidmain(String[]args)Stringstr="ThisisaStringIndexOutBounds";charch=str.charAt(30);}}////使用charAt()//java.lang.StringIndexOutOfBoundsException表示字符串索引越界異常。當(dāng)使用索引值某個(gè)字符長度減1,使用str已經(jīng)超過了其所以范圍,所以會(huì)StringIndexOutOfBoundsException異常。實(shí)例 當(dāng)在使用Arays.asist(時(shí)很容易會(huì)發(fā)生UnsupportedperaionExeption操作錯(cuò)誤異常本實(shí)例將演示操作錯(cuò)誤異常(ClassCasExeption)8.98.9在Eclipse中新建項(xiàng)目USOExcep,并在其中創(chuàng)建一個(gè)USOExcep.java文件。在該類的主方法中使publicclassUSOExceppublicstaticvoidmain(String[]args){String[]listArray=newString[2];Listlist=Listlist1=new//publicclassUSOExceppublicstaticvoidmain(String[]args){String[]listArray=newString[2];Listlist=Listlist1=new//使用Arrays.asList() //listlistArray[0]= //System.out.println(list.get(0 //}}}在使用 Arrays.asList()后調(diào)用 add()、remove()這些方法時(shí)會(huì)出現(xiàn)java.lang.UnsupportedOperationException異常。這是由于Arrays.asList()返回java.util.Arrays$ArrayList,而不是ArrayList。Arrays$ArrayList和ArrayList都是繼承 List(),remove(),add()等方法在List中是默認(rèn)拋出UnsupportedOperationException而且不作任何操作。ArrayListoverride這些方法來對list進(jìn)行操作,但是Arrays$ArrayList沒有overrideremove()add()等,所以會(huì)拋出UnsupportedOperationException實(shí)例 當(dāng)應(yīng)用試圖根據(jù)字符串形式的類名構(gòu)造類,而在遍歷CLASSPATH之后找不到對稱的class文ClassNotFoundException(ClassNotFoundException)8.10所示。8.10publicclassCNFExceppublicstaticvoidpublicclassCNFExceppublicstaticvoidmain(String[]args)throwsException{Connectionconn=null;Statementstmt=ResultSetrst=StringStrings=conn=DriverManager.getConnection(//stmt=//rst=stmt.executeQuery("select*fromwhile(rst.next()) //System.out.print(s=newString(rst.getString(1).getBytes("ISO-8859-1"),"GBK")+"--System.out.print(s=newString(rst.getString(2).getBytes("ISO-8859-1"),"GBK")+"--System.out.print(s=newString(rst.getString(3).getBytes("ISO-8859-1"),"GBK")+"--System.out.print(s=newString(rst.getString(4).getBytes("ISO-8859-1"),"GBK"));}}}java.lang.ClassNotFoundException表示找不到類異常。當(dāng)應(yīng)用試圖根據(jù)字符串形式的類名構(gòu)造類,而在遍歷CLASSPATH之后找不到對稱的class文件時(shí),拋出該異常。實(shí)例 try-catch捕獲異常的實(shí)try-catch8.11所示。8.11try-catchEclipseTryCatchTryCatch.javapublicclassTryCatchpublicstaticvoidmain(String[]args){intarray[]=publicclassTryCatchpublicstaticvoidmain(String[]args){intarray[]={0,1,2,3,4,5,6tryfor(inti=0;i<10;i++){System.out.println("array["+i+"]="+array[i]);}}catch(ArrayIndexOutOfBoundsExceptione)//////使用catchSystem.out.println("array[]的長度是array.length,數(shù)組下標(biāo)越界了}}}}}catch(異常類型異常對象名 }catch實(shí)例 try-catch-finally捕獲異常的實(shí)能夠根據(jù)錯(cuò)誤發(fā)生的類型決定應(yīng)該采取何種方式將程序恢復(fù)到正常的狀態(tài)。這一部分功能由Java的try-catch-finally結(jié)構(gòu)完成本實(shí)例將演示使用try-catch-finally捕獲異常的情況實(shí)例的運(yùn)行效果如圖8.128.12try-catch-finally。EclipseTryCatchFinallyTryCatchFinally.java文件。在該類的主方法中使用try-catch-finally捕獲數(shù)組元素不匹配異常,并增加finally語句輸出一串字符串代碼如。publicpublicclassTryCatchFinallypublicstaticvoidhasException(){Objectobj[]=newfor(inti=0;i<obj.length;i++){try{if(i%2==obj[i]=newobj[i]=newInteger(i)+"";System.out.print(""+obj[i]+"\n");}catch(ArrayStoreExceptione)////此句會(huì)發(fā)生ArrayStoreException//}}finally//執(zhí)行finally}}}publicstaticvoidmain(Stringargv[]) //}}catch(異常類型異常對象名}}有時(shí)為了確保一段代碼不管發(fā)生什么異常都要被catch(異常類型異常對象名}}。在finally的程序代碼塊運(yùn)行結(jié)束后,程序再回到try-catch-finally塊之后繼續(xù)執(zhí)行可以將上述8.13所示。。try{}是try{}是否捕到異塊中的語塊里的語程序語其他其他語8.13實(shí)例 嵌套try-catch捕獲異常實(shí)try-catch-finallytrytry、catchfinally部分。本實(shí)例將演示如何try-catch-finally8.14所示。8.14嵌套try-catchpublicclassNestTryCatchpublicstaticvoidmain(String[]args)publicclassNestTryCatchpublicstaticvoidmain(String[]args){intarray[]=newint[5];intn=for(inti=0;i<array.length;i++){array[i]=i;}for(inti=0;i<10;i++){try{tryn=array[i]/(i-}catch(ArithmeticExceptione)//5//使用for////0System.out.println("0不能做被除數(shù)");//}}catch(IndexOutOfBoundsExceptione)System.out.println("數(shù)組索引越界");//}}} 本實(shí)例主要應(yīng)用了try-catch-finally嵌套捕獲異常技術(shù)。一般嵌套的語法格式,可以用圖}catch(異常類象一定會(huì)運(yùn)行到的程序代}}catch(異常類象}8.15try-catch-finally將try-catch-finally嵌套在catch語句中是因?yàn)樵谔幚懋惓5臅r(shí)候很可能會(huì)新的異常。而這種嵌套的流程可以用圖8.16來解釋。}外層捕捉到異常進(jìn)入外層catch語句catch(異常類象全部處理完畢后,回到外層finally語句一定會(huì)運(yùn)行到的程序代}}catch(異常類象}8.16try-catch-finally實(shí)例 異常即IllegalArgumentException,當(dāng)不允許某類時(shí)發(fā)生。本實(shí)例將演示出現(xiàn)異常的情況。實(shí)例的運(yùn)行效果如圖8.17所示。(多余的空行,刪掉。圖8.17異publicclassIllAccessExceppublicstaticvoidpublicclassIllAccessExceppublicstaticvoidmain(String[]args){Class<?>clazz=String.class;Field[]fields=clazz.getDeclaredFields();for(Fieldfield:fields){if(field.getName().equals("hash")){try{}catch(IllegalArgumentExceptione){}catch(IllegalAccessExceptione)}}}}}//獲得代表String//獲得String////hash//捕獲IllegalArgumentException//捕獲IllegalAccessException類的權(quán)限便會(huì)出現(xiàn)這個(gè)異常對程序中用了package的情況下要注意特別這個(gè)異常。例如同一包中的其他類的時(shí)候,要注意public修飾的等等。實(shí)例 未發(fā)現(xiàn)文件異常即FileNotFoundException,當(dāng)要的文件找不到時(shí)發(fā)生。本實(shí)例將演示出現(xiàn)文件8.18所示。8.18publicclassFileNoFoundExceppublicstaticvoidmain(String[]args){FileInputStreamfis=null;tryFilefilepublicclassFileNoFoundExceppublicstaticvoidmain(String[]args){FileInputStreamfis=null;tryFilefile=newFile("d:\\lester.txt");fis=newFileInputStream(file);}catch(FileNotFoundExceptione){}finallytry}catch(IOExceptione){}}}//////// 實(shí)例 throws拋出異用的是throw語句,而在指定方法拋出異常時(shí),使用的是throws語句。先來看一個(gè)在指定方法中拋throws8.19所示。圖8.19throws異publicclassThrowsExceptionpublicstaticvoidmain(Stringargs[])trypublicclassThrowsExceptionpublicstaticvoidmain(Stringargs[])try//由于ShowExceptioncatch(Exceptione //使用catch \n"+"并在main方法中捕獲的異常+}}publicstaticvoidShowException()throwsException{Objectx=newInteger(0);System.out.println((String)x);}//}代碼塊內(nèi)。如果要由方法拋出異常,則方法必須用圖8.20所示的語法來。用throws8.20如果一個(gè)方法可以導(dǎo)致一個(gè)異常但不處理它它必須在方法時(shí)包含一個(gè)throws子句以使方法的對于除Error或RuntimeException及它們子類以外類型的所有異常都是必要的。一個(gè)方法的所有其他類型的異常必須在throws子句中,如果不這樣做,會(huì)導(dǎo)致編譯錯(cuò)誤。實(shí)例 throw拋出異throwthrow語句時(shí)立即終止,它后面的語句都不執(zhí)行。如果要捕捉throw拋出的異常,則必須使用try-catch語句。本例將演示出現(xiàn)使throw8.21所示。8.21throwEclipseThrowExceptionDemoThrowExceptionDemo.java文件。在該類的主方法中使用throw關(guān)鍵字拋出ThrowException拋出的異常。代碼如下所示:publicpublicclassThrowExceptionDemopublicstaticvoidmain(Stringargv[]){try{//由于}catch(Exceptione)"+""+}}publicstaticvoidThrowException(){doublea=Math.random();if(a<////0.2則輸出a0.2thrownew}}使用throw語句時(shí)必須一個(gè)異常對象,這個(gè)對象是Throwable派生類的對象,它的使用格式如throw 這里,ThrowableInstanceThrowableThrowable子類類型的一個(gè)對象。簡單類型如int、charThrowableStringObjectThrowable對象的方法:catchnewthrow語句之后立即停止;后面當(dāng)try語句塊拋出異常時(shí),首先檢測與try語句塊對應(yīng)的catch語句塊是否與該異常匹配。若檢測到catchtry-catch語句塊繼續(xù)檢測,以此類推。最后,如果沒有catch塊,程序中斷執(zhí)行并且打印堆棧軌跡。throw8.228.22拋出異常時(shí),throw關(guān)鍵字所拋出的是異常類的實(shí)例對象,因此要先用new關(guān)鍵字來產(chǎn)生一個(gè)實(shí)例 Exception類,所以自定義異常類也必須繼承這個(gè)類。本例將演示出現(xiàn)用戶自定義異常的情況。8.23所示。8.23publicclassUserDefineExceppublicstaticvoidmain(String[]args){try{thrownew//"Thisisthedefinitionofmyownexceptioncatch(userExceptione //userExceptionSystem.out.println("異常信息是:\npublicclassUserDefineExceppublicstaticvoidmain(String[]args){try{thrownew//"Thisisthedefinitionofmyownexceptioncatch(userExceptione //userExceptionSystem.out.println("異常信息是:\n}}}//classuserExceptionextendsException{publicuserException(Stringmessage){}}//8.24classclassextends}繼承Exception圖 自定義異常語Exception已提供相當(dāng)豐富的方法,通過繼承,子類均可使用它們。在JDK中提供的大量API方法之中的異常類,但這些類在實(shí)際開發(fā)中往往并不能滿足設(shè)實(shí)例 8.25所示。8.25publicclassSQLExceppublicstaticvoidmain(String[]args)StringURL="jdbc:mysql://localhost:3306/mysqltest";StringDRIVER="com.mysql.jdbc.Driver";StringUSERNAME=//MySQL//MySQLpublicclassSQLExceppublicstaticvoidmain(String[]args)StringURL="jdbc:mysql://localhost:3306/mysqltest";StringDRIVER="com.mysql.jdbc.Driver";StringUSERNAME=//MySQL//MySQL//MySQLStringStringPASSWORD=Connectionconn=null;try{MySQL//connDriverManager.getConnection(URLUSERNAMEPASSWORD)
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 散酒促銷活動(dòng)策劃方案(3篇)
- 線管鋼釘施工方案(3篇)
- 瀘州護(hù)欄施工方案(3篇)
- 2026天津市和平區(qū)面向社會(huì)公開選聘區(qū)管國有企業(yè)管理人員6人筆試參考題庫及答案解析
- 2026年荊州市沙市區(qū)事業(yè)單位人才引進(jìn)34人參考考試題庫及答案解析
- 健康同行護(hù)理科普同行
- 呼吸科護(hù)理工作中的安全管理
- 心內(nèi)科患者的出院指導(dǎo)
- 2026中國通號招聘3人(辦公室、戰(zhàn)略投資部)備考考試試題及答案解析
- 第四單元10沙灘上的童話
- 環(huán)境多因素交互導(dǎo)致慢性病共病的機(jī)制研究
- 2026湖南衡陽耒陽市公安局招聘75名警務(wù)輔助人員考試參考題庫及答案解析
- 2026年中共佛山市順德區(qū)委組織部佛山市順德區(qū)國有資產(chǎn)監(jiān)督管理局招聘備考題庫及參考答案詳解
- 多重耐藥菌醫(yī)院感染預(yù)防與控制技術(shù)指南完整版
- 2026年1月浙江省高考(首考)英語試題(含答案詳解)+聽力音頻+聽力材料
- 課例研究報(bào)告
- 五年級上冊道德與法治期末測試卷推薦
- 重點(diǎn)傳染病診斷標(biāo)準(zhǔn)培訓(xùn)診斷標(biāo)準(zhǔn)
- 蘭渝鐵路指導(dǎo)性施工組織設(shè)計(jì)
- CJJ82-2019-園林綠化工程施工及驗(yàn)收規(guī)范
- 小學(xué)三年級閱讀練習(xí)題《鴨兒餃子鋪》原文及答案
評論
0/150
提交評論