一、異常概述
異常是 Java 中的一個重要概念,它指的是程序在執行過程中出現的不正常狀況。Java 中的異常機制可以保證程序的健壯性,使得程序能夠更加穩定、可靠地運行。
Java 的異常可以分為兩類:受檢異常(checked exception)和非受檢異常(unchecked exception)。
- 受檢異常:就是必須顯式捕獲的異常,如果不處理會導致編譯錯誤。例如:IOException、SQLException 等。
- 非受檢異常:就是運行時異常,一般是程序員的錯誤導致。如果不處理,程序會在運行時崩潰。例如:NullPointerException、ArrayIndexOutOfBoundsException 等。
二、異常類型
1. NullPointerException
當一個對象為空,而你試圖訪問它的屬性、方法或子對象時,就會拋出 NullPointerException 異常。
public class NullPointerDemo { public static void main(String[] args) { String str = null; str.toString(); } }
上面的代碼中,str 為 null,調用它的 toString 方法會拋出 NullPointerException。
2. IndexOutOfBoundsException
當你訪問數組、字元串等容器類型時,如果訪問了一個不存在的元素、位置越界,就會拋出 IndexOutOfBoundsException 異常。
public class IndexOutOfBoundsDemo { public static void main(String[] args) { int[] arr = new int[3]; arr[3] = 1; } }
上面的代碼中,數組 arr 的長度為 3,訪問索引 3,越界了,會拋出 IndexOutOfBoundsException。
3. IllegalArgumentException
當你給一個方法傳遞了一個不合法的參數時,就會拋出 IllegalArgumentException 異常。
public class IllegalArgumentDemo { public static void main(String[] args) { int age = -5; if (age 150) { throw new IllegalArgumentException("年齡必須在0到150之間"); } } }
上面的代碼中,如果 age 小於 0 或大於 150,就會拋出 IllegalArgumentException。
4. ArithmeticException
當進行除法運算時,如果除數為 0,就會拋出 ArithmeticException 異常。
public class ArithmeticDemo { public static void main(String[] args) { int a = 10; int b = 0; int c = a / b; } }
上面的代碼中,除數 b 為 0,運行時會拋出 ArithmeticException 異常。
三、異常處理
1. try-catch-finally
Java 中使用 try-catch-finally 塊來處理異常。
public class TryCatchDemo { public static void main(String[] args) { try { int a = 10; int b = 0; int c = a / b; } catch (ArithmeticException e) { System.out.println("除數不能為 0"); } finally { System.out.println("這裡一定會執行"); } } }
在上面的代碼中,try 塊中的代碼可能會引發 ArithmeticException 異常,如果發生異常,就會跳轉到 catch 塊處理。finally 塊中的代碼一定會執行,無論是否有異常發生。
2. throws
如果一個方法中有可能拋出異常,可以使用 throws 關鍵字聲明異常的類型。
public class ThrowsDemo { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); System.out.println(line); } }
在上面的代碼中,readLine() 方法聲明了一個 IOException 異常,調用該方法時,必須在方法前使用 throws 關鍵字處理異常。
3. throw
程序員也可以手動拋出異常,使用 throw 關鍵字。
public class ThrowDemo { public static void main(String[] args) throws Exception { throw new Exception("異常信息"); } }
在上面的代碼中,使用 throw 關鍵字手動拋出了一個 Exception 異常。
四、總結
Java 異常可以分為受檢異常和非受檢異常。常見的異常類型包括:NullPointerException、IndexOutOfBoundsException、IllegalArgumentException、ArithmeticException 等。
異常處理可以使用 try-catch-finally 語句塊,也可以使用 throws 聲明異常類型。程序員還可以使用 throw 主動拋出異常。
原創文章,作者:KAYDE,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/317553.html