การจับข้อยกเว้น IndexOutOfRangeException ใน C#
IndexOutOfRangeException เกิดขึ้นเมื่อเข้าถึงอาร์เรย์ด้วยดัชนีที่อยู่นอกขอบเขต (น้อยกว่า 0 หรือมากกว่า/เท่ากับ Length)
สถานการณ์ที่เกิด Error
int[] n = new int[5] { 66, 33, 56, 23, 81 }; // Index 0-4
// พยายามเข้าถึง Index 0-9 -> Error ที่ Index 5
for (int j = 0; j < 10; j++)
{
Console.WriteLine($"Element[{j}] = {n[j]}"); // Crash ที่ j=5
}
ข้อความ Error
System.IndexOutOfRangeException: Index was outside the bounds of the array.
การจับข้อยกเว้นด้วย Try-Catch
using System;
namespace Demo
{
class MyArray
{
static void Main(string[] args)
{
try
{
int[] n = new int[5] { 66, 33, 56, 23, 81 };
for (int j = 0; j < 10; j++)
{
Console.WriteLine($"Element[{j}] = {n[j]}");
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Error: Index out of bounds!");
Console.WriteLine(e.Message);
}
}
}
}
ผลลัพธ์
Element[0] = 66
Element[1] = 33
Element[2] = 56
Element[3] = 23
Element[4] = 81
Error: Index out of bounds!
Index was outside the bounds of the array.
แนวทางป้องกัน (Best Practice)
- ตรวจสอบขอบเขตก่อนเข้าถึง:
if (index >= 0 && index < arr.Length) - ใช้ foreach แทน for index-based loop เมื่อไม่ต้องการ Index
- ใช้ List<T> ที่มี
Countและปลอดภัยกว่า - Try-Catch เฉพาะจุดที่อาจ Error ไม่ใช่ครอบทั้งโปรแกรม
โค้ดป้องกันแบบ Defensive
public static T SafeGet(T[] array, int index, T defaultValue = default)
{
return (index >= 0 && index < array.Length) ? array[index] : defaultValue;
}
// ใช้งาน
int[] arr = { 1, 2, 3 };
Console.WriteLine(SafeGet(arr, 5, -1)); // -1 (default) แทนที่จะ Crash