🙄🙄🙄✍👌
java中的異常分爲兩種:
1、運行異常
2、編譯異常
3、自定義異常(都屬上兩種)
1、先來看運行異常:
/**
* 場景一:
* 運行異常一般向上拋出,尤其爲寫公共接口等,
* 例如:編寫一個獲取字符串數組內某個字符
*/
public void ExceptionTest() {
String[] strArr = {"1", "2", "3"};
try {
//在這裏進行,異常捕獲,這是錯誤做法(×)
String str = PrintArrayToString(strArr, 5);
System.out.println("返回的字符是:" + str);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
/**
* 公共獲取數組內固定的某值
*
* @param arrays 數組
* @param sub 獲取下標號
* @return
* @throws java.lang.Exception
*/
public String PrintArrayToString(String[] arrays, int sub) throws java.lang.Exception {
//在這裏,便會存在數據越界問題,
//不予捕獲處理,向上拋出異常</span>
String str = arrays[sub];
return str;
}
開發注意:編寫公共接口的運行異常直接向上拋出,不要進行捕獲!!!
二、編譯異常沒啥好說,直接 try… catch
三、再來看自定義異常
/**
* 場景二:
* 自定義異常的寫法
* 1、創建異常類繼承RuntimeException,覆蓋其中的方法
* 2、在特定的條件下throw new 創建的異常,向上拋出
*/
public static void main(String[] args) {
try {
//這裏的調用會給拋出,我們的自定義異常
calculateDivision(10, 0);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
//計算除法division,throws java.lang.Exception,除了自定義異常外,其餘異常繼續向上拋出
private static int calculateDivision(int a, int b) throws java.lang.Exception {
//在這裏定義,自定義異常
if (b == 0) {
throw new customException("被除數不能爲0");
}
int c = a / b;
return c;
}
//自定義異常(繼承運行RuntimeException),覆寫其中的方法
static class customException extends RuntimeException {
public customException() {
super();
}
public customException(String message) {
super(message);
}
public customException(String message, Throwable cause) {
super(message, cause);
}
public customException(Throwable cause) {
super(cause);
}
protected customException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
over,over,over具體的註釋都放在了代碼裏了。😡