![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLwV3LcNXZnFWbp9CXt92YuI2bv5Wdy5yd3d3Lc9CX6MHc0RHaiojIsJye.gif)
Java 執行個體
對異常的處理:
1,聲明異常時,建議聲明更為具體的異常,這樣可以處理的更具體
2,對方聲明幾個異常,就對應幾個catch塊, 如果多個catch塊中的異常出現繼承關系,父類異常catch塊放在最下面
以下執行個體示範了如何處理多異常:
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)
catch (Exception e)//父類 寫在此處是為了捕捉其他沒預料到的異常 隻能寫在子類異常的代碼後面
//不過一般情況下是不寫的
System.out.println("Over");
以上代碼運作輸出結果為:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLwV3LcNXZnFWbp9CXt92YuI2bv5Wdy5yd3d3Lc9CX6MHc0RHaiojIsJye.gif)