IndexOutOfRangeException เกิดขึ้นเมื่อคุณพยายามเข้าถึงองค์ประกอบด้วยดัชนีที่อยู่นอกขอบเขตของอาร์เรย์
สมมติว่าต่อไปนี้คืออาร์เรย์ของเรา มี 5 องค์ประกอบ -
int [] n = new int[5] {66, 33, 56, 23, 81}; ตอนนี้ถ้าคุณจะพยายามเข้าถึงองค์ประกอบที่มีดัชนีมากกว่า 5 ข้อยกเว้น IndexOutOfRange จะถูกส่งออกไป -
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
} ในตัวอย่างข้างต้น เรากำลังพยายามเข้าถึงดัชนี 5 ข้างต้น ดังนั้นจึงเกิดข้อผิดพลาดดังต่อไปนี้ -
System.IndexOutOfRangeException:ดัชนีอยู่นอกขอบเขตของอาร์เรย์
นี่คือรหัสที่สมบูรณ์ -
ตัวอย่าง
using System;
namespace Demo {
class MyArray {
static void Main(string[] args) {
try {
int [] n = new int[5] {66, 33, 56, 23, 81};
int i,j;
// error: IndexOutOfRangeException
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
} catch (System.IndexOutOfRangeException e) {
Console.WriteLine(e);
}
}
}
} ผลลัพธ์
Element[0] = 66 Element[1] = 33 Element[2] = 56 Element[3] = 23 Element[4] = 81 System.IndexOutOfRangeException: Index was outside the bounds of the array. at Demo.MyArray.Main (System.String[] args) [0x00019] in <6ff1dbe1755b407391fe21dec35d62bd>:0
รหัสจะทำให้เกิดข้อผิดพลาด -
System.IndexOutOfRangeException −Index was outside the bounds of the array.