可在 Java 中處理 RuntimeException 嗎?
執行時異常或未經檢查的異常是執行時產生的異常。這些包括程式設計錯誤,如邏輯錯誤或 API 使用不當。編譯時會忽略執行時異常。
IndexOutOfBoundsException、ArithmeticException、ArrayStoreException 以及 ClassCastException 是執行時異常的示例。
示例
在以下 Java 程式中,我們有一個大小為 5 的陣列,並且嘗試訪問第 6 個元素,這會生成 ArrayIndexOutOfBoundsException。
public class ExceptionExample {
public static void main(String[] args) {
//Creating an integer array with size 5
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//Accessing index greater than the size of the array
System.out.println( inpuArray[6]);
}
}執行時異常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at MyPackage.ExceptionExample.main(ExceptionExample.java:14)
處理執行時異常
你可以處理執行時異常並避免異常終止,但是,Java 中沒有針對執行時異常的具體修復,根據異常型別,你需要更改程式碼。
例如,如果你需要修復上面列出的第一個程式中的 ArrayIndexOutOfBoundsException,你需要移除/更改訪問超出其大小的陣列索引位置的行。
public class ExceptionExample {
public static void main(String[] args) {
//Creating an integer array with size 5
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//Accessing index greater than the size of the array
System.out.println( inpuArray[3]);
}
}輸出
26
廣告
資料結構
網路技術
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP