package com.liujunhua.it01;
/**
* 對多異常的處理:
* 1.聲明異常時,建議聲明更爲具體的異常,這樣處理的時候可以處理的更具體。
* 2.被調用的函數有幾個異常,就對應幾個catch塊,不要定義多餘的代碼塊。
* 如果多個catch塊中的異常出現繼承關係,父類異常放在最下面。
*
* 建立catch處理時,catch中的一定要定義具體的處理方式。不用簡單的定義
* 一句 e.printStackTrace();也不要簡單的定義一句輸出語句
*/
public class Demo03 {
public static void main(String[] args) {
ExceptionTest exceptionTest = new ExceptionTest();
try {
int x = exceptionTest.div(4, 0);
System.out.println("x = " + x);
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println(e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
System.out.println("**********************");
}
}
class ExceptionTest {
//這裏聲明並拋出了多個異常
int div(int a, int b) throws ArithmeticException ,ArrayIndexOutOfBoundsException{
int[] arr = new int[a];
System.out.println(arr[4]);
return a / b;
}
}
異常初探(三)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.