




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
異常處理
異?;靖拍钕到y異常類用戶自定義異常異常處理異常轉移一、異常處理機制當方法執行過程中出現錯誤而干擾了程序流程時,會拋出一個異常,即構造出一個異常類的對象。異常類對象代表當前出現的一個具體異常,該對象封裝了異常的有關信息。異常分為系統定義異常和用戶自定義異常。異常拋出方式:系統定義異常-自動拋出用戶自定義異常-用throw語句拋出方法中的異常處理:捕獲異常,就地解決,并使程序繼續執行。將異常向外轉移,即將異常拋出方法之外,由調用該方法的環境去處理。程序中的異常處理可以提高程序的健壯性二、異常與異常類Throwable類Exception類Error類自定義異常類ArrayIndexOutOfBoundsException
類NullPointerException
類...1.系統異常類的層次結構2.系統定義的異常類Error類定義的錯誤是致命性錯誤,一般會導致程序停止執行。Exception類定義的是較輕的錯誤,你可以編寫代碼來處理這類錯誤,并繼續程序的執行。系統預定義異常類及含義系統預定義的異常類異常對應的運行錯誤說明ClassNotFoundException類型轉換異常:如找不到要裝載的類。IllegalArgumentException非法參數異常:可用于檢查方法參數的合法性。ArrayIndexOutOfBoundsException下標越界異常:一般指數組下標越界。FileNotFoundException找不到文件異常:未找到指定的文件或目錄。IOException輸入輸出異常:在輸入輸出操作時產生的異常。NullPointerException空指針異常:訪問空的尚未實例化的引用型變量。ArithmeticException數學異常:如數學運算被零除等。SecurityException安全性異常:如Applet小程序要讀寫文件。3.Exception類構造函數Exception()Exception(String異常描述)方法StringgetMessage()
-返回異常描述StringtoString()
-返回異常對象詳細信息。voidprintStackTrace()
打印異常發生的路徑,即引起異常的方法調用嵌套序列4.用戶定義異常類用戶自定義異常主要用來處理用戶程序中特定的邏輯運行錯誤。定義異常類:classMyExpextendsException{//或繼承其他異常類
...//定義新的屬性
...//重載構造函數
...//重載原方法,或定義新方法
}例1:用戶自定義異常。下面代碼定義一個異常類,用于表示超時異常。classTimeOutExceptionextendsException
{ privateStringreason; privateStringip; privateintport;
publicTimeOutException(Strings,StringserverIP,intserverPort) { reason=s; ip=serverIP; port=serverPort; }
publicStringgetReason(){ returnreason; } publicStringgetIp(){ returnip; } publicintgetPort(){ returnport; } publicStringtoString() { return"Exception:ipis"+ip+"portis"+port+"thereasonis"+reason;
}}4.用戶定義異常類定義好異常類后,程序中就可以拋出、捕獲并處理該類型的異常publicclassExceptionTest{ publicstaticvoidmain(String[]args) {
try {
thrownewTimeOutException(”Connecttimeout”,”166.111.8.28”,80); }
catch(TimeOutExceptione) {
System.out.println(e);
} }}三、異常處理概念:警戒區-可能會引起異常的代碼段
try{
警戒區代碼(try塊) //拋出異常
}catch(ExceptTypee){ //捕獲異常 異常處理代碼 //處理異常
}
后續語句若try塊中沒有異常,則try塊執行完,控制轉向后續語句。若try塊中出現異常,則控制轉向下面的異常處理部分,然后執行后續語句。要捕獲的異常類對象1.拋出異常
(1)系統自動拋出異常例2:系統自動拋出異常。publicclassa{ publicstaticvoidmain(String[]args) { inti; int[]array={21,33,52,44,98}; try { while(true) { i=(int)(Math.random()*10); System.out.println(”下標為”+i+”的數組元素是”+array[i]);} } catch(ArrayIndexOutOfBoundsExceptione) {
System.out.println(”出現數組下標越界異?!?;
} }}系統自動拋出異常。publicclassa{ publicstaticvoidmain(String[]args) { int[]array={21,33,52,44,98}; try { System.out.println(array[6]); } catch(ArrayIndexOutOfBoundsExceptione) {
System.out.println(”出現數組下標越界異常”);
} }}(2)直接拋出異常(throw語句)適用于用戶自定義異常格式: 生成異常類的實例e; throwe;或: thrownew異常類構造方法例3:直接拋出異常。publicclassThrowException{ publicstaticvoidmain(String[]args) {
try{ thrownewArithmeticException(); } catch(ArithmeticExceptione){System.out.println(e);}
try{ thrownewArrayIndexOutOfBoundsException();} catch(ArrayIndexOutOfBoundsExceptione){ System.out.println(e); } System.out.println("throwanexception"); }}(3)間接拋出異常(throws)也稱為異常轉移異??偸前l生在方法執行過程中。當方法代碼不對異常處理時,異常會向方法外轉移。系統定義的異常自動向外轉移。用戶自定義的異常要轉移需要在方法頭聲明一下例4:間接拋出異常(throws)。publicclassThrowsException{ publicstaticvoidmain(String[]args)throwsRuntimeException {
try{ thrownewArithmeticException(); } catch(ArithmeticExceptione) { System.out.println("throwexception:"+e); } throwsException();
System.out.println("throwsexception");//沒有執行 }
staticvoidthrowsException()throwsRuntimeException { try{thrownewArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsExceptione) { System.out.println("throwexception:"+e);
thrownewArrayIndexOutOfBoundsException(); } }}(4)檢查型異常處理(5)運行時異常運行時異常都繼承自RuntimeException類publicdoubledivide(inta,intb){returna/b;}try{ //可能出現異常的代碼}catch(異常類型1e1){ //處理異常類型1}catch(異常類型2e2){ //處理異常類型2}……catch(異常類型3e3){ //處理異常類型3}finally{ //該代碼塊在try塊執行后完成必做的事情}2.異常的捕獲與處理例5:從鍵盤讀取兩個整數,用第一個整數除以第二個整數,并輸出結果。如果在程序讀取數據的過程中發生異常,則將捕獲該異常并處理。importjava.io.*;publicclassCatchException{ publicstaticintgetInteger() { BufferedReaderinput=new BufferedReader(newInputStreamReader(System.in));
try{returnInteger.parseInt(input.readLine().trim()); } catch(Exceptione){ e.printStackTrace();//輸出異常的方法調用棧 return0; } } publicstaticvoidmain(String[]args) { intn,d,r; System.out.println("EnteroneInteger:"); n=getInteger(); System.out.println("EnteranotherInteger:"); d=getInteger();
try{ r=n/d; System.out.println(n+"/"+d+"="+r); } catch(ArithmeticExceptione){e.printStackTrace();} System.out.println("endofprogram"); }}3.多異常處理try{...}//可處理多種異常catch(異常類1e1){...}catch(異常類2e2){...}滿足異常匹配的條件:拋出對象與catch參數類型相同拋出對象為catch參數類的子類多異常處理中的匹配順序:按先后順序捕獲(注意catch塊書寫時的排列順序:先具體、后一般),但只捕獲一次。例6:使用多重catch語句classMultiCatch{publicstaticvoidmain(Stringargs[]){try{inta=args.length;System.out.println("a="+a);intb=42/a;intc[]={1};c[42]=99;}catch(ArithmeticExceptione){System.out.println("Divideby0:"+e);}catch(ArrayIndexOutOfBoundsExceptione){System.out.println("Arrayindexoob:"+e);}System.out.println("Aftertry/catchblocks.");}}練習:分析程序運行結果classF1{publicstaticvoidmain(Stringargs[]){try{inta=0;System.out.println("a="+a);intb=42/a;intc[]={1};c[42]=99;}catch(ArithmeticExceptione){System.out.println("Divideby0");}catch(ArrayIndexOutOfBoundsExceptione){System.out.println("Arrayindexoob");}System.out.println("Aftertry/catchblocks.");}}例7:異常處理例-未作異常處理publicclassTest{publicstaticvoidmain(String[]args){TestExceptionte=newTestException();te.m1();//調用m1方法,對m1方法的異常未做處理
}}classTestException{
privateinti;privateint[]array={1,2,3,4,5};//定義一個含5個元素的數組
voidm1(){//該方法中會出現數組下標越界異常,且無處理
for(intj=0;j<10;j++){
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 周圍血管病復習試題有答案
- 城市地理研究項目計劃
- 春節期間環境保護項目工期保障措施
- 2025年施工員之市政施工基礎知識模擬考試試卷A卷含答案
- 2025新人教版五年級下冊美術教學計劃
- 2025年酒店銷售業績提升總結與計劃
- 江東中學九年級下學期科學開學檢測試卷
- 七上科學第四單元多種多樣的運動拔高培優試卷B(新版)
- 八年級第二學期科學期未測試試題卷
- 體育與藝術結合的一年級教學計劃
- 2025屆福建省漳州市高三第三次教學質量檢測生物試卷(解析版)
- 2025年茶葉加工工職業技能競賽參考試題庫500題(含答案)
- 2025甘肅陜煤集團韓城煤礦招聘250人筆試參考題庫附帶答案詳解
- 《設計課件:構建高效數據集教程》
- 2025江蘇中考:歷史高頻考點
- 普通測量學試題及答案
- 國家開放大學2025年《創業基礎》形考任務3答案
- 醫療器械網絡銷售質量管理規范宣貫培訓課件2025年
- 語文課程資源的開發與利用
- 2024年09月四川天府新區人民醫院招聘6人筆試歷年專業考點(難、易錯點)附帶答案詳解
- SL631水利水電工程單元工程施工質量驗收標準第1部分:土石方工程
評論
0/150
提交評論