異常處理
- 如何處理異常
1. try-catch-finally
2. throw
3. throws
4. 自定義異常
5. 異常鍊
根類:Throwable
兩個子類:Error、Exception
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcugjN0YWZhRTNyUTY5ADM2EDZilzYkNjYkZmNzY2Y0UDOfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
image.png
上圖中非檢查異常,表示的是編譯器不要求強制處理的異常,包括:
檢查異常:在程式編碼階段就被要求必須進行異常處理,否則編譯無法通過。
Java中異常通過五個關鍵字來實作:
- try
- catch
- finally
- throw
- throws
Java入門之異常處理
try-catch-finally
public class TryDemo {
public static void main(String[] args){
int a = 10;
int b = 0;
try {
int c = a/b;
}catch (ArithmeticException e){
System.out.println("出錯了");
}finally {
System.out.println("一定會執行");
}
}
}
使用多重catch結構處理異常
public class TryDemo {
public static void main(String[] args){
int a = 10;
int b = 0;
try {
int c = a/b;
}catch (ArithmeticException e){
System.out.println("出錯了");
}catch (Exception e){
System.out.println("33333");
}
finally {
System.out.println("一定會執行");
}
}
}
Exception 父類異要放在最後一個catch塊中。
注意:如果在finally塊中和catch塊中都有return語句,最終隻會執行finally中的return,不會執行catch塊中的return。在代碼編寫中不建議把return放到finally塊中。
使用throws聲明異常類型
public class TryDemo {
public static void main(String[] args){
try {
int result = test();
}catch (ArithmeticException e){
System.out.println(e);
}catch (InputMismatchException e){
System.out.println(e);
}
}
public static int test() throws ArithmeticException, InputMismatchException{
System.out.println("d");
}
}
使用throw抛出異常對象
throw抛出的隻能是可抛出類Throwable或者其子類的執行個體對象。
當方法當中包含throw抛出對象的語句時,正常的處理方法有兩種:
方法一:
public void method(){
try{
throw new 異常類型();
}catch(異常類型 e){
//處理異常
}
}
方法二:誰調用了目前的方法誰就來處理異常
public void method() throws 異常類型{
throw new 異常類型();
}
自定義異常類
使用Java内置的異常類可以描述在程式設計時出現的大部分異常情況。
也可以通過自定義異常描述特定業務産生的異常類型。
- 所謂自定義異常,就是定義一個類去繼承Throwable類或它的子類。
異常鍊
有時候我們在捕獲一個異常後再抛出另一個異常。
異常鍊:将異常發生的原因一個傳一個串起來,即把底層的異常資訊傳給上層 ,這樣逐層抛出。