1. 程式人生 > >自定義異常

自定義異常

sum tom 什麽是 -c 創建 聲明 自定義 void main

一:什麽是自定義異常

自定義異常就是自己定義的異常類,也就是Exception直接或間接的子類。

二:怎麽使用自定義異常

(1)創建自定義異常類

(2)在方法中通過throw 關鍵字拋出自定義異常

(3)如果在當前拋出異常的方法中處理異常,可以使用try-catch語句捕獲並處理,否則在方法的聲明處通過throws關鍵字聲明該異常

(4)調用throws聲明該異常的方法時,使用try catch捕獲自定義的異常類型,並在catch中進行處理

public class TestThrow {


static void sum(int a,int b) throws Exception{
//如果數字為負數的話就拋出數學異常
if(a<0||b<2){
throw new CustomException("不能使用負數");
}
if(a>100||b>100){
throw new CustomException(“數值太大了”);
}
//輸入的數字正確的話就打印另個數的和
System.out.println(a+b);

}


public static void main(String[] args){


try {
TestThrow.sum(100, 6);
} catch (Exception e) {
System.out.println("數字不能為負數"); }


}

自定義異常