1. 程式人生 > >java基礎(七)throw與throws

java基礎(七)throw與throws

一、兩者的定義
throw
throw是語句丟擲一個異常,一般是在程式碼塊的內部,當程式出現某種邏輯錯誤時由程式設計師主動丟擲某種特定型別的異常。

public static void main(String[] args) { 
    String s = "abc"; 
    if(s.equals("abc")) { 
      throw new NumberFormatException(); 
    } else { 
      System.out.println(s); 
    } 
    //function(); 
}

執行時,系統會丟擲異常:
Exception in thread “main” java.lang.NumberFormatException at…
throws


throws是方法可能丟擲異常的宣告。(用在宣告方法時,表示該方法可能要丟擲異常)。

public void function() throws Exception{......}

當某個方法可能會丟擲某種異常時用於throws 宣告可能丟擲的異常,然後交給上層呼叫它的方法程式處理。

public class testThrows {
 
    public static void function() throws NumberFormatException {
        String s = "abc";
        System.out.println(Double.parseDouble(s));
    }
 
    public static void main(String[] args) {
        try {
            function();
        } catch (NumberFormatException e) {
            System.err.println("非資料型別不能強制型別轉換。");
            //e.printStackTrace(); 
        }
    }
}

執行結果:
非資料型別不能強制型別轉換。
二、throw與throws的比較
throws出現在方法函式頭;而throw出現在函式體。
throws表示出現異常的一種可能性,並不一定會發生這些異常;throw則是丟擲了異常,執行throw則一定丟擲了某種異常物件。
兩者都是消極處理異常的方式(這裡的消極並不是說這種方式不好),只是丟擲或者可能丟擲異常,但是不會由函式去處理異常,真正的處理異常由函式的上層呼叫處理。
三、程式設計習慣
在寫程式時,對可能會出現異常的部分通常要用try{…}catch{…}去捕捉它並對它進行處理;
用try{…}catch{…}捕捉了異常之後一定要對在catch{…}中對其進行處理,那怕是最簡單的一句輸出語句,或棧輸入e.printStackTrace();
如果是捕捉IO輸入輸出流中的異常,一定要在try{…}catch{…}後加finally{…}把輸入輸出流關閉;
如果在函式體內用throw丟擲了某種異常,最好要在函式名中加throws拋異常宣告,然後交給呼叫它的上層函式進行處理。

參考:
Java中關鍵字throw和throws的區別