Java 實例 - 多個異常處理(多個catch)
對異常的處理:
1,聲明異常時,建議聲明更為具體的異常,這樣可以處理的更具體
2,對方聲明幾個異常,就對應幾個catch塊, 如果多個catch塊中的異常出現繼承關係,父類異常catch塊放在最下麵
以下實例演示了如何處理多異常:
ExceptionDemo.java 檔
class Demo
{
int div(int a,int b) throws ArithmeticException,ArrayIndexOutOfBoundsException//在功能上通過throws的關鍵字聲明該功能可能出現問題
{
int []arr = new int [a];
System.out.println(arr[4]);//製造的第一處異常
return a/b;//製造的第二處異常
}
}
class ExceptionDemo
{
public static void main(String[]args) //throws Exception
{
Demo d = new Demo();
try
{
int x = d.div(4,0);//程式運行截圖中的三組示例 分別對應此處的三行代碼
//int x = d.div(5,0);
//int x = d.div(4,1);
System.out.println("x="+x);
}
catch (ArithmeticException e)
{
System.out.println(e.toString());
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}
catch (Exception e)//父類 寫在此處是為了捕捉其他沒預料到的異常 只能寫在子類異常的代碼後面
//不過一般情況下是不寫的
{
System.out.println(e.toString());
}
System.out.println("Over");
}
}
以上代碼運行輸出結果為:
java.lang.ArrayIndexOutOfBoundsException: 4 Over