如何在Java中處理ArrayStoreException(非受檢異常)?
java.lang.ArrayStoreException 是一個非受檢異常,當試圖將某種型別的物件儲存到不同型別的物件陣列中時,可能會發生此異常。通常,你會遇到java.lang.ArrayStoreException: java.lang.Integer,這種情況發生在嘗試將整數儲存到不同型別的陣列中時,例如字串陣列或浮點數陣列等。
示例1
public class ArrayStoreExceptionTest {
public static void main(String[] args) {
Object[] names = new Float[2];
names[1] = new Integer(2);
}
}輸出
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at ArrayStoreExceptionTest.main(ArrayStoreExceptionTest.java:4)
在上述程式中,發生了java.lang.ArrayStoreException: java.lang.Integer
- java.lang.ArrayStoreException: 當嘗試將java.lang.Integer型別的物件儲存到java.lang.Float型別的陣列中時,Java 語言丟擲的異常。
- java.lang.Integer: 嘗試儲存到不同型別陣列中的Integer型別物件。
如何處理ArrayStoreException
我們可以使用try...catch 塊來處理ArrayStoreException。
- 用try...catch 塊包圍可能丟擲ArrayStoreException的語句。
- 我們可以捕獲ArrayStoreException。
- 對我們的程式採取必要的措施,因為我們正在處理異常,並且執行不會中斷。
示例2
public class ArrayStoreExceptionTest {
public static void main(String[] args) {
Object[] names = new Float[2];
try {
names[1] = new Integer(2);
} catch (ArrayStoreException e) {
e.printStackTrace();
System.out.println("ArrayStoreException is handled");
}
System.out.println("Continuing with the statements after try and catch blocks");
}
}輸出
ArrayStoreException is handled Continuing with the statements after try and catch blocks java.lang.ArrayStoreException: java.lang.Integer at ArrayStoreExceptionTest.main(ArrayStoreExceptionTest.java:5)
在上面的例子中,當發生異常時,執行從異常發生點跳轉到catch塊。它執行catch塊中的語句,然後繼續執行try...catch塊後面的語句。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP