ใน Java มี ArrayIndexOutOfBoundsException ใน C# เทียบเท่าคือ IndexOutOfRangeException (ไม่มี "Bounds" ในชื่อ) เกิดเมื่อเข้าถึง Array ด้วย Index ไม่ถูกต้อง
ตัวอย่างที่ทำให้เกิด Exception
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[3]; // Index 0, 1, 2
arr[0] = 5;
arr[1] = 7;
arr[2] = 8;
// ERROR: Index 4 ไม่มีอยู่ (Max = 2)
arr[4] = 24; // IndexOutOfRangeException
}
}
}
ผลลัพธ์
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
ความแตกต่าง Java vs C#
| คุณสมบัติ | Java | C# |
|---|---|---|
| Exception Name | ArrayIndexOutOfBoundsException | IndexOutOfRangeException |
| Inheritance | extends IndexOutOfBoundsException | extends Exception (โดยตรง) |
| Array Access Check | Runtime (JVM) | Runtime (CLR) |
| Zero-based | ใช่ | ใช่ |
การป้องกัน (เหมือนกันทั้งคู่)
- ตรวจสอบ
index >= 0 && index < array.Lengthก่อนเข้าถึง - ใช้
foreachแทน Index-based Loop - ใช้
List<T>ที่มีCountProperty ชัดเจน - Unit Test Edge Cases (Empty, Single, Boundary)
หมายเหตุ: C# มี ArgumentOutOfRangeException สำหรับ Collection Methods (List.Insert, String.Substring, etc.) ที่แยกจาก IndexOutOfRangeException (สำหรับ Array Indexer โดยตรง)