4、throw與throws
shrow:手動拋出異常
語法:throw 異常對象
throw new Exception("異常信息...........");
throw new MyException("自定義異常.........")
throws:聲明異常
在定義方法時,同時給方法聲明一個異常
public void insert(int i, Object data) throws Exception{
? ? if(i < 0){
? ? ? ? throw new Exception("下標不合法");
? ? }
}
通過throws聲明異常后,若調用該方法,則需要處理該異常
public void insert(int i, Object data) throws Exception{
? ? if(i < 0){
? ? ? ? throw new Exception("下標不合法");
? ? }
}
public void add(int i, Object data){
? ? // 需要處理異常
? ? try{
? ? ? ? insert(i, data);
? ? } catch(Exception e){
? ? ? ??
? ? }
}
所有聲明式異常都是檢查異常,在編碼時,就需要處理,否則語法出錯
throw和throws可以同時出現,也可以單獨出現,當throw單獨出現時,可將throw語句放入try語句中直接進行異常處理;當throws單獨出現時,可直接加在方法后面
5、自定義異常
自己寫一個異常類型,處理特定異常問題
自定義異常需要繼承Throwsable類或者Exception類(通常繼承此類)
public class UserException extends Exception{
? ? public UserException(String messgae) {
? ? ? ? super(messgae);
? ? }
}
做完自己的異常類后,在需要異常的方法中就可以通過throw語句來拋出該異常,拋出的異常可以直接throws掉讓調用方處理或者直接try...catch
掉
public static void main(String[] args) throws Exception{
? ? int i = 5;
? ? if (i > 0){
? ? ? ? throw new MyException("錯誤");
? ? }
}
// 或者
public static void main(String[] args){
? ? int i = 5;
? ? if (i > 0){
? ? ? ? try {
? ? ? ? ? ? throw new MyException("錯誤");
? ? ? ? } catch (MyException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
}
? ? throw 與 throws區別
throw為手動拋出異常,指運行到該語句就拋出異常,不往下執行,或者可以通過try...catch處理該異常,例如打印日志和異常堆棧信息
throws為聲明式異常,在定義時,在方法的后面通過throws 指定異常類型,此時,調用該方法必須去處理該異常