Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

IndexOutOfRangeException ใน C#: ข้อยกเว้นดัชนีเกินขอบเขต

IndexOutOfRangeException เป็น Exception ที่โยนเมื่อเข้าถึง Array/Collection ด้วย Index ที่อยู่นอกขอบเขต (น้อยกว่า 0 หรือ มากกว่าหรือเท่ากับ Length)

สาเหตุทั่วไป

  • Index เริ่มที่ 0 (Zero-based) - Index สูงสุดคือ Length - 1
  • Off-by-one Error ใน Loop
  • Array ว่าง (Length = 0) แต่พยายามเข้าถึง Index 0
  • คำนวณ Index ผิดพลาด

ตัวอย่างที่ทำให้เกิด Exception

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[5]; // Index 0-4
            
            arr[0] = 10;
            arr[1] = 20;
            arr[2] = 30;
            arr[3] = 40;
            arr[4] = 50;
            
            // ERROR: Index 5 ไม่มีอยู่ (Max Index = 4)
            arr[5] = 60; // IndexOutOfRangeException
        }
    }
}

ผลลัพธ์ (Exception)

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

วิธีป้องกันและแก้ไข

1. ตรวจสอบ Bounds ก่อนเข้าถึง

if (index >= 0 && index < arr.Length)
{
    var value = arr[index];
}

2. ใช้ foreach แทน for index (เมื่อไม่ต้องการ Index)

foreach (var item in arr)
{
    Console.WriteLine(item);
}

3. ใช้ Try/Catch (Defensive)

try
{
    return arr[index];
}
catch (IndexOutOfRangeException)
{
    return default; // หรือ Handle ตาม Logic
}

4. ใช้ Array.GetValue/SetValue (ส่งคืน Exception เหมือนกันแต่ปลอดภัยกว่าในบางกรณี)

// ยังโยน Exception หาก Out of Bounds

5. Span/Bounds Checking (High Performance)

Span span = arr;
if (span.Length > index) { ... }

Debugging Tips

  • เปิด Exception Settings ใน Visual Studio (Ctrl+Alt+E) → ✓ Common Language Runtime Exceptions → จับได้ทันทีที่โยน
  • ดู Call Stack และ Index Value ที่ Error
  • ใช้ Debug.Assert(index >= 0 && index < arr.Length) ใน Debug Build