Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Xử lý ngoại lệ IndexOutOfRangeException trong C#

IndexOutOfRangeException ném ra khi truy cập mảng/collection với index < 0 hoặc >= Length. Đây là lỗi logic (bug), nên sửa code tránh xảy ra thay vì chỉ catch.

Ví dụ gây lỗi

using System;

class Program
{
    static void Main()
    {
        int[] n = { 66, 33, 56, 23, 81 }; // Length = 5, index 0..4
        
        // LỖI: vòng lặp đến 9 (index 5..9 ngoài phạm vi)
        for (int j = 0; j < 10; j++)
        {
            Console.WriteLine($"Element[{j}] = {n[j]}"); // Crash tại j=5
        }
    }
}

Kết quả lỗi

Element[0] = 66
Element[1] = 33
Element[2] = 56
Element[3] = 23
Element[4] = 81
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

Cách 1: Sửa vòng lặp (Best Practice - ngăn chặn bug)

// Dùng Length property
for (int j = 0; j < n.Length; j++)
    Console.WriteLine($"Element[{j}] = {n[j]}");

// Hoặc foreach (không cần index)
foreach (int val in n)
    Console.WriteLine(val);

// Hoặc for với index (C# 7+ tuple deconstruction)
for (int i = 0; i < n.Length; i++)
    Console.WriteLine($"[{i}] = {n[i]}");

Cách 2: Kiểm tra trước khi truy cập (Defensive)

static void SafeAccess(int[] arr, int index)
{
    if (index >= 0 && index < arr.Length)
        Console.WriteLine($"Element[{index}] = {arr[index]}");
    else
        Console.WriteLine($"Index {index} ngoài phạm vi [0, {arr.Length - 1}]");
}

Cách 3: Try-catch (Chỉ khi không thể kiểm tra trước)

using System;

class Program
{
    static void Main()
    {
        int[] n = { 66, 33, 56, 23, 81 };
        
        try
        {
            // Code có thể ném exception (ví dụ index từ input người dùng/file)
            int idx = int.Parse(Console.ReadLine());
            Console.WriteLine($"Element[{idx}] = {n[idx]}");
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine($"Lỗi: Index {ex.Message}");
            // Log, fallback, retry...
        }
        catch (FormatException)
        {
            Console.WriteLine("Lỗi: Nhập không phải số");
        }
    }
}

Best Practices

  1. Ưu tiên sửa logic: Dùng .Length, .Count, foreach thay vì hard-code số.
  2. Validate input sớm: Kiểm tra index trước khi dùng.
  3. Không catch IndexOutOfRangeException để che lấp bug logic. Chỉ catch khi index từ nguồn bên ngoài (user input, file, network).
  4. Dùng ArgumentOutOfRangeException cho validation tham số method (thay vì để IndexOutOfRangeException tự ném).

Lưu ý

  • List<T> ném ArgumentOutOfRangeException (kế thừa từ IndexOutOfRangeException) khi index sai.
  • C# 8+: Index và Range an toàn hơn: arr[^1] (phần tử cuối), arr[1..4] (sub-range).