運行時異常(RuntimeException 子類)是編程中最常見的 Bug 來源。本文通過 switch-case 依次觸發四大經典異常,演示 try-catch 捕獲與 getMessage() 信息輸出,幫助初學者建立異常識別直覺。
public class ExceptionDemo2 {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
int k = 0; // 佔位變量,避免編譯警告
switch (i) {
case 0: // 算術異常:除數為零
try {
int zero = 0;
k = 911 / zero;
} catch (Exception e) {
System.out.println("算術異常,分母不能為零:" + e.getMessage());
}
break;
case 1: // 空指針異常:操作 null 對象
try {
int[] arr = null;
k = arr[0]; // 訪問 null 數組元素
} catch (Exception e) {
System.out.println("空指針異常:" + e.getMessage());
}
break;
case 2: // 數組索引越界:訪問不存在下標
try {
int[] arr = new int[2]; // 長度 2,合法下標 0,1
k = arr[9]; // 訪問下標 9
} catch (Exception e) {
System.out.println("索引超出範圍:" + e.getMessage());
}
break;
case 3: // 字符串索引越界:charAt 超出長度
try {
char ch = "abc".charAt(99); // 長度 3,合法 0,1,2
} catch (Exception e) {
System.out.println("索引超出範圍:" + e.getMessage());
}
break;
}
}
}
}
算術異常,分母不能為零:/ by zero
空指針異常:null
索引超出範圍:Index 9 out of bounds for length 2
索引超出範圍:String index out of range: 99
| 異常類 | 父類 | 觸發場景 | getMessage() 典型輸出 | 避免策略 |
|---|---|---|---|---|
ArithmeticException | RuntimeException | 整數除零(浮點數除零返回 Infinity) | / by zero | 除法前檢查除數 != 0 |
NullPointerException | RuntimeException | 調用 null 對象方法/屬性、訪問 null 數組元素 | null (通常為空) | 使用前非空判斷、Optional、@NonNull 註解、Objects.requireNonNull() |
ArrayIndexOutOfBoundsException | IndexOutOfBoundsException | 數組下標 < 0 或 >= length | Index 9 out of bounds for length 2 | 循環邊界檢查、foreach 迭代、List 替代數組 |
StringIndexOutOfBoundsException | IndexOutOfBoundsException | 字符串 charAt/substring 索引非法 | String index out of range: 99 | 調用前檢查 str.length() |
try {
// 高風險代碼
} catch (ArithmeticException | NullPointerException e) {
// 處理算術與空指針
log.error("計算或引用錯誤", e);
} catch (IndexOutOfBoundsException e) {
// 捕獲父類覆蓋數組/字符串越界
log.error("索引越界", e);
}
try (FileInputStream fis = new FileInputStream("a.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
// 使用資源
} catch (IOException e) {
// 自動關閉 fis、br,無需 finally
}
public class InsufficientBalanceException extends RuntimeException {
public InsufficientBalanceException(String msg) { super(msg); }
}
// 使用
if (balance < amount) throw new InsufficientBalanceException("餘額不足,當前:" + balance);
Run → View Breakpoints → + → Java Exception Breakpoint 勾選 ArithmeticException 等,拋出瞬間自動斷點定位源碼行。catch (Exception e) { } 空 catch 塊是重大隱患,至少記錄日誌。