Java異常類可以分為兩大類:檢查異常和非檢查異常。
檢查異常是指在程序中可能會出現的異常,需要在代碼中進行捕捉和處理。非檢查異常是指運行期才會出現的異常,不需要強制捕捉處理。
Java異常類及其繼承關係如下圖所示:

一、常見異常類
1. NullPointerException
當一個應用程序試圖在需要對象的地方使用 null 時,將引發該異常。
public class NullPointer {
public static void main(String[] args) {
String str = null;
System.out.println(str.length());
}
}
2. ArrayIndexOutOfBoundsException
當一個應用程序試圖訪問數組的索引超出範圍時,將引發該異常。
public class ArrayIndex {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(arr[3]);
}
}
3. ClassCastException
當一個應用程序試圖將一個對象強制轉換為不是該對象當前類或其子類的類型時,將引發該異常。
public class ClassCast {
public static void main(String[] args) {
Object obj = "Hello";
Integer num = (Integer) obj;
}
}
4. ArithmeticException
當一個應用程序試圖執行算術運算,而這個運算的第二個操作數為零時,將引發該異常。
public class Arithmetic {
public static void main(String[] args) {
int a = 10, b = 0;
int c = a / b;
}
}
二、捕獲異常
Java提供了 try-catch 塊來捕獲異常。try 塊中包含可能會出現異常的代碼,一旦發生異常,catch 塊中的代碼將會被執行。
1. 單個異常
public class TryCatch {
public static void main(String[] args) {
int num1 = 10, num2 = 0;
try {
int result = num1 / num2;
System.out.println("結果是:" + result);
} catch (ArithmeticException e) {
System.out.println("除數不能為零");
}
System.out.println("程序結束");
}
}
2. 多個異常
public class TryCatch {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
arr[3] = 4;
Object obj = "Hello";
Integer num = (Integer) obj;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("數組越界");
} catch (ClassCastException e) {
System.out.println("類型轉換異常");
}
System.out.println("程序結束");
}
}
三、拋出異常
在程序中,如果出現了無法處理的異常,可以使用 throw 關鍵字將異常拋出,在調用該方法的地方使用 try-catch 塊捕獲異常。
1. 拋出檢查異常
public class ThrowCheck {
public static void main(String[] args) throws FileNotFoundException {
FileReader reader = new FileReader("file.txt");
}
}
2. 拋出非檢查異常
public class ThrowUncheck {
public static void main(String[] args) {
int num1 = 10, num2 = 0;
if (num2 == 0) {
throw new ArithmeticException("除數不能為零");
}
int result = num1 / num2;
System.out.println("結果是:" + result);
}
}
四、總結
Java異常處理機制可以幫助我們在程序出現異常時及時處理,避免程序崩潰。在編寫程序時,應該儘可能考慮到可能出現的異常,並進行捕獲和處理,避免出現異常後無法恢復的情況。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/286181.html