JavaSE入門學習26:Java異常處理分析(下)
七throws/throw關鍵字
如果一個方法沒有捕獲一個檢查性異常,那麼該方法必須使用throws 關鍵字來聲明。throws關鍵字放在方法簽名
的尾部。也可以使用throw關鍵字拋出一個異常,無論它是新執行個體化的還是剛捕獲到的。throw將產生的異常拋出(動
作);throws——聲明將要拋出何種類型的異常(聲明)。
下面方法的聲明拋出一個RemoteException異常:
import java.io.*;public class ClassName{public void deposit(double amount) throws RemoteException{//Method implementation throw new RemoteException(); } //Remainder of class definition}
一個方法可以聲明拋出多個異常,多個異常之間用逗號隔開。
例如,下面的方法聲明拋出RemoteException和InsufficientFundsException:
import java.io.*;public class ClassName{ public void withdraw(double amount) throws RemoteException,InsufficientFundsException // Method implementation } //Remainder of class definition}
八finally關鍵字
finally關鍵字用來建立在try代碼塊後面執行的代碼塊。無論是否發生異常,finally代碼塊中的代碼總會被執行。在
finally代碼塊中,可以運行清理類型等收尾善後性質的語句。finally代碼塊出現在catch代碼塊最後,文法如下:
try{ // 程式碼}catch(異常類型1 異常的變數名1){ // 程式碼}catch(異常類型2 異常的變數名2){ // 程式碼}finally{ // 程式碼}
執行個體:Test.java源檔案代碼:
public class Test{public static void main(String args[]){int a[] = new int[2]; try{System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); }finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } }}
以上執行個體編譯運行結果如下:
捕獲的異常是數組下標越界。而finally塊中的語句依然執行。
使用注意下面事項:
1)catch不能獨立於try存在。
2)在try/catch後面添加finally塊並非強制性要求的。
3)try代碼後不能既沒catch塊也沒finally塊。
4)try, catch, finally塊之間不能添加任何代碼。
九自訂異常
在Java中你可以自訂異常。編寫自己的異常類時需要記住下面的幾點:
1)所有異常都必須是Throwable的子類。
2)如果希望寫一個檢查性異常類,則需要繼承Exception類。
3)如果你想寫一個運行時異常類,那麼需要繼承RuntimeException 類。
使用自訂異常一般步驟如下步驟:
1通過繼承java.lang.Exception類聲明自己的異常類。
2在方法適當的位置產生自訂異常的執行個體,並用throw語句拋出。
3在方法的聲明部分用throws語句聲明該方法可能拋出的異常。
可以像下面這樣定義自己的異常類:
class MyException extends Exception{}
只繼承Exception 類來建立的異常類是檢查性異常類。
下面的InsufficientFundsException類是使用者定義的異常類,它繼承自Exception。一個異常類和其它任何類一樣,
包含有變數和方法。
執行個體:
InsufficientFundsException.java源檔案代碼:
import java.io.*;public class InsufficientFundsException extends Exception{ private double amount; public InsufficientFundsException(double amount){this.amount = amount; } public double getAmount(){ return amount; }}
為了展示如何使用我們自訂的異常類,
在下面的CheckingAccount 類中包含一個withdraw()方法拋出一個InsufficientFundsException異常。
CheckingAccount.java源檔案代碼:
import java.io.*;public class CheckingAccount{ private double balance; private int number; public CheckingAccount(int number){this.number = number; } public void deposit(double amount){ balance += amount; } public void withdraw(double amount) throws InsufficientFundsException{if(amount <= balance){balance -= amount; }else{double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance(){return balance; } public int getNumber(){return number; }}
下面的BankDemo程式示範了如何調用CheckingAccount類的deposit() 和withdraw()方法。
BankDemo.java源檔案代碼:
public class BankDemo{public static void main(String [] args){CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try{ System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e){ System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } }}
編譯上面三個檔案(在同一個包內),並運行程式BankDemo,得到結果如下所示:
十通用異常
在Java中定義了兩種類型的異常和錯誤。
JVM(Java虛擬機器)異常:由JVM拋出的異常或錯誤。例如:NullPointerException類,
ArrayIndexOutOfBoundsException類,ClassCastException類。
程式級異常:由程式或者API程式拋出的異常。例如IllegalArgumentException類,IllegalStateException類。
十一處理異常經驗
1處理運行時異常是,採用邏輯去合理規避同時輔助try-catch處理。
2在多重catch塊後面,可以加一個catch(Exception)來處理可能會被遺漏的異常。
3對於不確定的代碼,也可以加上try-catch,處理潛在的異常。
4盡量取處理異常,切忌只是簡單的調用printStackTrace()去列印輸出。
5具體如何處理異常,要根據不同的業務需求和異常類型去決定。
6盡量添加finally語句塊去釋放佔用的資源。