標籤:
編寫自訂異常類實際上是繼承一個API標準異常類,用新定義的異常處理資訊覆蓋原有資訊的過程。常用的編寫自訂異常類的模式如下: public class CustomException extends Exception { //或者繼承任何標準異常類 public CustomException() {} //用來建立無參數對象 public CustomException(String message) { //用來建立指定參數對象 super(message); //調用超類構造器 }} 當然也可選用Throwable作為超類。其中無參數構造器為建立預設參數對象提供了方便。第二個構造器將在建立這個異常對象時提供描述這個異常資訊的字串,通過調用超類構造器向上傳遞給超類,對超類中的toString()方法中返回的原有資訊進行覆蓋。來討論一個具體例子。假設程式中需要驗證使用者輸入的表示年齡的資料必須是正整數值。我們可以按照以上模式編寫這個自訂異常類如下: public class NegativeAgeException extends Exception { //或者:extends Throwable public NegativeAgeException() {} public NegativeAgeException(String message) { super(message); }} 下面是應用這個自訂異常類的例子: //完整程式存在本書配套資來源目錄為Ch11中名為NegativeAgeExceptionTest.java...try{ String ageString = JOptionPane.showInputDialog("Enter your age: "); if (Integer.parseInt(ageString) < 0) throw new NegativeAgeException("Please enter a positive age"); else JOptionPane.showMessageDialog(null, ageString, "Age", 1);}catch(NegativeAgeException e){ System.out.println(e);}... 或者,可以建立一個預設對象,然後在catch中列印具體資訊,如: throw new NegativeAgeException(); ...catch (NegativeAgeException e) { System.out.println("Please enter a positive age"); 將產生與第一個例子相同的效果。 無論是利用標準API異常類來處理特殊的異常,或者編寫自訂的異常類來達到同樣目的,問題的關鍵是:<!--[if !supportLists]-->1. <!--[endif]-->當這個異常發生時,如何及時捕獲這個異常。<!--[if !supportLists]-->2. <!--[endif]-->捕獲這個異常後,如何產生精確的異常處理資訊。 毋庸置疑,我們不可能期待JVM自動拋出一個自訂異常,也不能夠期待JVM會自動處理一個自訂異常。發現異常、拋出異常以及處理異常的工作必須靠編程人員在代碼中利用異常處理機制自己完成。一般情況下,發現和拋出一個自訂異常通過在try程式塊中利用if和throw陳述式完成,即: try { ... if (someExceptionConditon == true) { throw new CustomException("A custom exception xxx occurred. Please check your entry...") ... }catch (CustomException e) { ...} 而列印異常處理資訊可以在拋出時包括在構造器的參數中,或者包括在處理這個異常的catch中。另外應該注意在自訂異常發生之前,有可能產生標準異常的情況。例如,在一個需要驗證年齡必須是正整數值的程式中,利用自訂異常類,如NegativeAgeException,驗證輸入的年齡是否正整數,即: try { ... if (Integer.parseInt(ageString) < 0) throw NegativeAgeException("Please enter a positive age"); else ... } catch (NumberFormatException e) { System.out.println(e); } catch (NegativeAgeException e) { System.out.println(e); } ... 注意在這個代碼中,如果ageString是非法整數字串,如“25ab”,系統將首先拋出NumberFormatException,而不會執行throw NegativeAgeException("Please enter a positive age")。所以應該在catch中加入對NumberFormatException的處理,如以上代碼所示。
[轉]如何編寫和應用Java的自訂異常類