摘要:例子二以下開始用異常處理機制捕獲該異常在這里,這個其實就是這里用到了程序運行時的多態(tài)思想。語句就像一個調(diào)用函數(shù),當程序運行中拋出了一個異常對象,就會調(diào)用對應(yīng)的來處理。
傳統(tǒng)的語言如何處理
在一些傳統(tǒng)的語言(如C語言中)
if語句來判斷是否出現(xiàn)了例外
全程變量ErrNo
但這有幾個缺點
正常處理與異常處理的代碼同樣處理
可讀性(readability)差
每次調(diào)用一個方法時都進行錯誤檢查
可維護性( maintainability )差錯誤由誰處理不請
職責不清
Java中的異常處理特點:Java中處理異常包括
拋出(throw)異常
運行時系統(tǒng)在調(diào)用棧中查找
從生成異常的方法開始進行回溯,直到找到:
捕獲(catch) 異常的代碼
調(diào)用過程如下所示:
沒有使用Java異常處理機制
public class Test { public static void main(String [] args){ for(int i = 0; i < 2;i++){ System.out.print(i + " "); System.out.println(1/0);//throw an exception. } } }
運行結(jié)果:
0 Exception in thread "main" java.lang.ArithmeticException: / by zero
1/0明顯非法,所以產(chǎn)生了異常ArithmeticException對象,這個對象是Exception的子類。
例子二以下開始用異常處理機制捕獲該異常:
public class Test { public static void main(String [] args){ for(int i = 0; i < 2;i++){ System.out.print(i + " "); try{ System.out.println(1/0);//An exception will throw from here. } catch(Exception ex){//在這里,這個Exception 其實就是ArithmeticException //這里用到了程序運行時的多態(tài)思想。 //實際中應(yīng)指定具體的作為ex的類型,更加有針對性。 System.out.println("exception handling...");// } } } }
運行結(jié)果:
0 exception handling... 1 exception handling...
這樣確實能捕獲到相應(yīng)的異常對象。盡管什么也沒做(只是打印字符串),卻讓編譯器不再報告之前的異常。因為上述catch(type ex){...}就是負責處理異常。
例子三當捕獲到異常后,程序的運行過程會怎樣?
public class Test2 { public static void main(String[] args){ try{ for (int i = 0; i< 2; i++){ System.out.print(i + " "); System.out.println(1/0);//exception being thrown from here.Then it wil jump directly to the corresponding catch block. System.out.println("This line is supposed to be ignored"); } } //handling the exception. catch(Exception ex){ System.out.println("Exception handling..."); } System.out.println("End of the main()"); } }
運行結(jié)果:
0 exception handling... End of the main()
當for不可能循環(huán)到i = 2;因為在i = 1時已經(jīng)拋出了異常。只要產(chǎn)生了異常,轉(zhuǎn)入對應(yīng)的catch(type ex){...}。catch(type ex)必須在參數(shù)里面說明捕獲的對象是哪類型的。
throw語句就像一個調(diào)用函數(shù),當程序運行中拋出了一個異常對象,就會調(diào)用對應(yīng)的catch(type ex){}來處理。但它又不像調(diào)用函數(shù)。因為在調(diào)用完后,它不會返回到throw語句,而是接著catch之后的語句。所以System.out.println("This line is supposed to be ignored");這條語句被沒有執(zhí)行;for循環(huán)也相當于被中斷了。
拋出異常
throw 異常對象;
捕獲異常
try{ 語句組 } catch(異常類名 異常形式參數(shù)名){ 異常處理語句組; } catch(異常類名 異常形式參數(shù)名){ 異常處理語句組; } finally{ 異常處理語句組; }
其中,catch語句可以0至多個,可以沒有finally語句
異常的分類Throwable
Error: JVM的錯誤(一般來說,我們很難處理這里異常)
Exception: 異常(重點關(guān)注)
注:一般所說的異常,是指Exception及其子類
構(gòu)造方法
public Exception(); public Exception(String message); Exception(String message, Throwable cause) ;
方法
getMessage() getCause() printStackTrace()代碼 例子一
仍然是沒有使用Java的異常處理機制:
import java.util.Scanner; public class QuotientWithMethod { public static int quotient(int num1, int num2){ if(num2 == 0){ log("Divisor cannot be zero"); System.exit(1); } return num1/num2; } public static void log(String s){ System.out.println(s); } public static void main(String[] args){ Scanner input = new Scanner(System.in); //prompt user to enter two integers int num1 = input.nextInt(); int num2 = input.nextInt(); int result = quotient(num1,num2);//調(diào)用函數(shù) System.out.println(num1 + "/" + num2 + "is" + result ); } }
運行結(jié)果
input two numbers: 1 0 Divisor cannot be zero
在沒用使用異常處理機制的情況下,出現(xiàn)了異常情況的話,在被調(diào)用的函數(shù)中,處理異常情況——這里是直接退出了程序;
例子二用異常處理機制的好處是職責分明:被調(diào)函數(shù)中拋出異常,主調(diào)函數(shù)中負責處理異常。
import java.util.Scanner; public class QuotientWithException { public static int quotient(int num1, int num2){ if(num2 == 0){ throw new ArithmeticException("Divisor cannot be zero");//用關(guān)鍵字throw拋出異常對象,這里是調(diào)用構(gòu)造器來新建對象 }//但不做處理 return num1/num2; } public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.println("input two numbers:"); int num1 = input.nextInt(); int num2 = input.nextInt(); boolean goOn = true; do { try { int result = quotient(num1, num2); System.out.println("num1" +"/" + "num2" + "is" +result); goOn = false; } //職責分明;一個負責拋出異常,一個負責處理異常. catch(ArithmeticException ex){ //在主調(diào)函數(shù)中處理異常 System.out.println("Exception occur:" + "Divisor cannot be zero. input again,please:"); num1 = input.nextInt(); num2 = input.nextInt(); //int result = quotient(num1, num2); //System.out.println("num1" +"/" + "num2" + "is" +result); } }while(goOn); //處理后,進入catch{}后的語句. System.out.println("End of main()."); } }
運行結(jié)果
input two numbers: 1 0 Exception occur:Divisor cannot be zero. input again,please: 1 1 num1/num2is1 End of main().
在被調(diào)函數(shù)中,只負責拋出異常:throw new ArithmeticException("Divisor cannot be zero");,主調(diào)函數(shù)中catch(ArithmeticException ex){...}指定將要捕獲的對象的類型,并做相應(yīng)的處理,這里要求重新輸入。
多異常的處理子類異常要排在父類異常的前面,也就是先處理具體的異常,后處理抽象的異常。
finally語句,無論是否有異常都要執(zhí)行,即使其中有break,return等語句
在編譯時,finally部分代碼生成了多遍
Exception分兩種RuntimeException及其子類,可以不明確處理;否則,稱為受檢的異常(checked Exception)
RuntimeException, Error, and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with them in a try-catch block or declare it in the method header.--Introduction to Java
對于受檢的異常(checked Exception),要求明確進行語法處理:
要么捕(catch)
要么拋(throws):在方法的簽名后面用throws xxxx來聲明
在子類中,如果要覆蓋父類的一個方法,若父類中的方法聲明了 throws異常,則子類的方法也可以throws異常
可以拋出子類異常(更具體的異常),但不能拋出更一般的異常
自定義異常類創(chuàng)建用戶自定義異常時
繼承自Exception類或某個子Exception類
定義屬性和方法,或重載父類的方法
這樣getMessage(), toString(), printStackTrace()都會從Exception繼承下來。
重拋異常及異常鏈接( Chained Exceptions)對于異常,不僅要進行捕獲處理,有時候還需要將此異常進一步傳遞給調(diào)用者,以 便讓調(diào)用者也能感受到這種異常。這時可以在catch語句塊或finally語句塊中采取,以下三種方式:
將當前捕獲的異常再次拋出:
throw e;
重新生成一個異常,并拋出,如:
throw new Exception("some message");
重新生成并拋出一個新異常,該異常中包含了當前異常的信息,如:throw new Exception("some message",e);用e.getCause() 來得到內(nèi)部異常
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://hztianpu.com/yun/65915.html
摘要:不受檢查異常為編譯器不要求強制處理的異常,檢查異常則是編譯器要求必須處置的異常。潛在的異常處理器是異常發(fā)生時依次存留在調(diào)用棧中的方法的集合。當運行時系統(tǒng)遍歷調(diào)用棧而未找到合適的異常處理器,則運行時系統(tǒng)終止。異常處理涉及到五個關(guān)鍵字,分別是。 概念 程序運行時,發(fā)生的不被期望的事件,它阻止了程序按照程序員的預(yù)期正常執(zhí)行,這就是異常。 異常是程序中的一些錯誤,但并不是所有的錯誤都是異常,并...
摘要:異常也就是指程序運行時發(fā)生錯誤,而異常處理就是對這些錯誤進行處理和控制。有兩個重要的子類異常和錯誤,二者都是異常處理的重要子類,各自都包含大量子類。需要注意的是,一旦某個捕獲到匹配的異常類型,將進入異常處理代碼。 1,異?,F(xiàn)象 程序錯誤分為三種:1,編譯錯誤;2,運行時錯誤;3,邏輯錯誤。 編譯錯誤是因為程序沒有遵循語法規(guī)則,編譯程序能夠自己發(fā)現(xiàn)并且提示我們錯誤的原因和位置,這...
摘要:根據(jù)異常對象判斷是否存在異常處理。否則,范圍小的異常會因異常處理完成而無法處理。異常處理中使用作為異常的統(tǒng)一出口。 參考《第一行代碼java》《java程序設(shè)計教程》java中程序的錯誤有語法錯誤、語義錯誤。如果是語法性錯誤,在編譯時就可以檢查出來并解決。語義錯誤是在程序運行時出現(xiàn)的,在編譯時沒有錯誤,但在運行時可能會出現(xiàn)錯誤導(dǎo)致程序退出,這些錯誤稱為異常。在沒有異常處理的情況下,也即...
摘要:為可恢復(fù)的錯誤使用檢查型異常,為編程錯誤使用非檢查型錯誤。檢查型異常保證你對錯誤條件提供異常處理代碼,這是一種從語言到強制你編寫健壯的代碼的一種方式,但同時會引入大量雜亂的代碼并導(dǎo)致其不可讀。在編程中選擇檢查型異常還是運行時異常。 異常處理是Java 開發(fā)中的一個重要部分。它是關(guān)乎每個應(yīng)用的一個非功能性需求,是為了處理任何錯誤狀況,比如資源不可訪問,非法輸入,空輸入等等。Java提供了...
閱讀 4242·2021-11-23 10:09
閱讀 1490·2021-11-23 09:51
閱讀 3128·2021-11-23 09:51
閱讀 1815·2021-09-07 09:59
閱讀 2535·2019-08-30 15:55
閱讀 2472·2019-08-30 15:55
閱讀 3101·2019-08-30 15:52
閱讀 2702·2019-08-26 17:04