1. 程式人生 > 實用技巧 >異常的捕獲和丟擲

異常的捕獲和丟擲

try-catch必須要有

finally可以不要,假設有io,一般在這裡關閉

若要捕獲多個異常:catch應該從小到大排列

快捷鍵:選中這行程式碼ctrl+alt+T ,選擇相應選項,則自動包裹該程式碼

方法裡丟擲用throw ,方法上丟擲用throws。

以上關鍵詞的具體用法在下方程式中清楚展示:

package exception.demon1;

public class demon1 {

public static void main(String[] args) {
    int a = 9;
    int b = 0;

    try {//監控區域

        if(b==0){
            throw new ArithmeticException(); //丟擲異常
        }

        System.out.println(a / b);


    } catch //捕獲異常
    (ArithmeticException e) { //(想要捕獲的異常型別 自定名)
        System.out.println("出錯啦");
        //方法區
    } catch (Exception e){
        System.out.println("Exception");
    }catch (Throwable e){
        System.out.println("Throwable");}
    finally { //處理善後工作 終究會被執行
        System.out.println("不管有沒出錯都輸出這句話");
    }
    //最終輸出: 出錯啦

// 不管有沒出錯都輸出這句話

    new demon1().div(10,0);        //呼叫除法方法

}
//假設這個方法中,處理不了這個異常。就在"方法上丟擲異常"
public int div(int a,int b) throws AbstractMethodError //"方法上丟擲異常"
{
    if(b==0){
        throw new ArithmeticException(); //主動丟擲異常
                                         //即使沒有除法方法體,只要b滿足等於0這個條件,就丟擲異常
                                         //一般用於方法中
    }

    int result = a/b;
    System.out.println(result);
    return result;

}

}