天天速看:【學懂Java】(五)異常處理

2023-01-24 17:26:36 來源:51CTO博客

一.引入

編寫程序時會有各種各樣的錯誤,例如

該程序在被除數為0的時候,就會不正確。我們可以這樣解決


(資料圖)

但是這樣也有弊端:

代碼臃腫程序員要花很大精力“堵漏洞”程序員很難堵住所有“漏洞”

因此需要引入異常機制

二.異常處理機制

1.注意

Java編程語言使用異常處理機制為程序提供了錯誤處理的能力Java的異常處理是通過5個關鍵字來實現的:try、catch、finally、throw、throws程序在運行過程中如果出現了問題,會導致后面的代碼無法正常執行,而使用異常機制之后,可以對異常情況進行處理同時后續的代碼會繼續執行,不會中斷整個程序在異常的處理過程中,不要只是簡單的輸出錯誤,要盡可能的講詳細的異常信息進行輸出e.printStackTrace():打印異常的堆棧信息,可以從異常信息的最后一行開始追蹤,尋找自己編寫的java類

2.捕獲異常

try-catch

try{代碼邏輯}catch(Exception e){異常處理邏輯}

try{代碼邏輯}catch(具體的異常Exception e){異常處理邏輯}catch(具體的異常):

可以針對每一種具體的異常做相應的更豐富的處理 注意:當使用多重的catch的時候一定要注意相關異常的順序,將子類放在最前面的catch,父類放在后面的catch

使用try-catch塊捕獲異常,分為三種情況:

正常執行,只執行try中的代碼 遇到異常情況,會處理try中異常代碼之前的邏輯,后面的邏輯不會執行,最后會執行catch中的代碼 使用多重catch的時候,會遇到異常子類不匹配的情況,此時依然會報錯,因此建議在catch的最后將所有的異常的父類寫上

我們將之前的例子改進一下

public class TestException {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        try {            System.out.print("請輸入被除數:");            int num1 = in.nextInt();            System.out.print("請輸入除數:");            int num2 = in.nextInt();            System.out.println(String.format("%d / %d = %d",                    num1, num2, num1 / num2));            System.out.println("前面沒有出現異常");        /*}catch(Exception e){            System.out.println("出現異常");            e.printStackTrace();//輸出相關異常信息,比如行數            System.out.println(e.getMessage());        }*/       }catch(ArithmeticException e){            System.out.println("數學異常,除數不能是0");            e.printStackTrace();        }catch (InputMismatchException e){            System.out.println("輸入的參數值類型不匹配");            e.printStackTrace();        }catch (NullPointerException e){            System.out.println("空指針異常");            e.printStackTrace();        }        System.out.println("感謝使用本程序");    }}

try-catch-finally

在程序運行過程中,如果處理異常的部分包含finally的處理,那么無論代碼是否發生異常,finally中的代碼總會執行

finally包含哪些處理邏輯?

IO流的關閉操作一般設置在finally中數據庫的連接關閉操作設置在finally中
public class FinallyDemo {    public static void main(String[] args) {    }    public static void test(){        try{            System.out.println(1/10);            return;        }catch (Exception e){            e.printStackTrace();            return;        }finally {            System.out.println("我是finally");            return;        }    }}

3.聲明異常

throws:聲明異常

在異常情況出現的時候,可以使用try...catch...finally的方式對異常進行處理,除此之外,可以將異常向外拋出,由外部進行處理

1、在方法調用過程中,可以存在N多個方法之間的調用,此時假如每個方法中都包含了異常情況

那么就需要在每個方法中都進行try。。catch,另外一種比較簡單的方式,就是在方法的最外層調用處理一次即可使用throws的方法,對所有執行過程中的所有方法出現的異常進行統一集中處理

2、如何判斷是使用throws還是使用try...catch..

最穩妥的方式是在每個方法中都進行異常的處理偷懶的方式是判斷在整個調用的過程中,外層的調用方法是否有對異常的處理,如果有,直接使用throws,如果沒有那么就要使用try...catch...
public class Excepton2 {    public static void main(String[] args) {        try {            show();        } catch (Exception e) {            e.printStackTrace();        }        System.out.println("ll");    }        public static void test1() throws Exception{        System.out.println(1/0);    }    public static void test2() throws Exception {        test1();        System.out.println(100/0);    }    public static void test3() throws Exception{        test2();    }    public static void test4() throws Exception{        test3();    }}

4.拋出異常

throw:拋出異常

public class Excepton2 {    public static void main(String[] args) {        try {            show();        } catch (Exception e) {            e.printStackTrace();        }        System.out.println("hehe");    }    public static void show() throws Exception{        String gender = "12";        if (gender.equals("man")){            System.out.println("man");        }else if(gender.equals("woman")){            System.out.println("woman");        }else{            throw new Exception("性別出現錯誤");        }    }}

自定義異常

在java的api中提供了非常豐富的異常類,但是在某些情況下不太滿足我們的需求,此時需要自定義異常

步驟:

繼承Exception類 自定義實現構造方法需要使用的時候,使用throw new 自定義異常的名稱;

什么時候需要自定義異常?

一般情況下不需要,但是在公司要求明確,或者要求異常格式規范統一的時候是必須要自己實現的

public class GenderException extends Exception {    public GenderException(){        System.out.println("性別異常");    }    public GenderException(String msg){        System.out.println(msg);    }}
public class Excepton2 {    public static void main(String[] args) {        try {            show();        } catch (GenderException e) {            e.printStackTrace();        }        System.out.println("hehe");    }    public static void show() throws GenderException{        String gender = "12";        if (gender.equals("man")){            System.out.println("man");        }else if(gender.equals("woman")){            System.out.println("woman");        }else{//          throw new Exception("性別出現錯誤");            throw new GenderException("gender is wrong");        }    }}

5.異常的分類

標簽: 自定義異常 異常處理 異常情況

上一篇:天天最新:【Redis技術專區】「優化案例」談談使用Redis慢查詢日志以及Redis慢查詢分析指南
下一篇:天天要聞:【學懂Java】(四)面向對象編程-6