java.lang.ArrayStoreException เป็น ไม่ถูกตรวจสอบ ข้อยกเว้น และอาจเกิดขึ้นได้เมื่อเราพยายามเก็บวัตถุประเภทหนึ่งไว้ในอาร์เรย์ของวัตถุประเภทอื่น โดยปกติ จะเจอ java.lang.ArrayStoreException:java.lang.Integer ซึ่งเกิดขึ้นเมื่อพยายามเก็บจำนวนเต็มในอาร์เรย์ประเภทต่าง ๆ เช่นอาร์เรย์ของสตริงหรืออาร์เรย์ของ float เป็นต้น
ตัวอย่าง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.lang.Integer: จำนวนเต็มคือประเภทของอ็อบเจ็กต์ที่ได้รับการพยายามจัดเก็บอาร์เรย์ประเภทอื่น
วิธีจัดการ ArrayStoreException
เราสามารถจัดการกับ ArrayStoreException ใช้ลองจับ บล็อค
- ล้อมรอบข้อความสั่งที่สามารถโยน 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 block จากจุดที่เกิดข้อยกเว้น มันรันคำสั่งในบล็อก catch และดำเนินการต่อด้วยคำสั่งที่มีอยู่หลังจากบล็อก try และ catch