Java"異常"總結

Java中什麼是異常?

異常通常指的是可能是你的代碼在編譯的時候沒有任何錯誤,但是在運行時會出現一些異常。也可能是一些無法預料到的異常。
有些錯誤是這樣的, 例如將 System.out.println 拼寫錯了, 寫成system.out.println. 此時編譯過程中就會出 錯, 這是 “編譯期” 出錯.而運行時指的是程序已經編譯通過得到 class 文件了, 再由 JVM 執行過程中出現的錯誤.

異常的種類有很多, 不同種類的異常具有不同的含義, 也有不同的處理方式.
我們寫代碼會遇到各種各樣的異常,比較常見的有以下幾種異常:

除以0
System.out.println(10 / 0);

//執行結果
Exception in thread "main" java.lang.ArithmeticException: / by zero

數組下標越界

int[] arr = {1, 2, 3, 4};
System.out.println(arr[4]);

//執行結果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

訪問null

public class Test {
    public int num = 10;
    public static void main(String[] args) {
        Test test = null;
        System.out.println(test.num);
    }
}

//執行結果
Exception in thread "main" java.lang.NullPointerException

異常的基本語法

try {
	可能出現異常的代碼語句;
} catch (異常的類型 異常的對象) {
	處理異常的代碼;
} finally {
	異常的出口;
}

**注意⚠️:**一旦 try 中出現異常, 那麼 try 代碼塊中的程序就不會繼續執行, 而是交給 catch 中的代碼來執行. catch 執行完畢會繼續往下執行.而且 finally 中的代碼一定都會執行到,所以不建議在 finally 中有返回語句。

異常處理流程

  • 程序先執行 try 中的代碼
  • 如果 try 中的代碼出現異常, 就會結束 try 中的代碼, 看和 catch 中的異常類型是否匹配.
  • 如果找到匹配的異常類型, 就會執行 catch 中的代碼
  • 如果沒有找到匹配的異常類型, 就會將異常向上傳遞到上層調用者.
  • 無論是否找到匹配的異常類型, finally 中的代碼都會被執行到(在該方法結束之前執行).
  • 如果上層調用者也沒有處理的了異常,就繼續向上傳遞.
  • 一直到 main 方法也沒有合適的代碼處理異常, 就會交給 JVM 來進行處理, 此時程序就會異常終止.

拋出異常

除了 Java 內置的類會拋出異常,我們也可以手動拋出一個異常。使用 throw 關鍵字完成這個操作。

public static void main(String[] args) {
    System.out.println(divide(10, 0));
}
public static int divide(int x, int y) {
    if (y == 0) {
		throw new ArithmeticException("拋出除 0 異常"); 
	}
	return x / y;
}
// 執行結果
Exception in thread "main" java.lang.ArithmeticException: 拋出除 0 異常
    at demo02.Test.divide(Test.java:14)
    at demo02.Test.main(Test.java:9)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章