krahets/hello-algo · error · IndexOutOfRangeException

索引越界

Error message

索引越界

What it means

IndexOutOfRangeException with message "索引越界" (index out of bounds) is thrown by Get(int index) on a custom dynamic-array MyList implementation when the supplied index is less than 0 or greater than or equal to arrSize (the current logical element count). It protects the backing arr[] from invalid access. The message is in Chinese, matching the source-language pedagogical convention.

Source

Thrown at codes/csharp/chapter_array_and_linkedlist/my_list.cs:35

    public MyList() {
        arr = new int[arrCapacity];
    }

    /* 获取列表长度(当前元素数量)*/
    public int Size() {
        return arrSize;
    }

    /* 获取列表容量 */
    public int Capacity() {
        return arrCapacity;
    }

    /* 访问元素 */
    public int Get(int index) {
        // 索引如果越界,则抛出异常,下同
        if (index < 0 || index >= arrSize)
            throw new IndexOutOfRangeException("索引越界");
        return arr[index];
    }

    /* 更新元素 */
    public void Set(int index, int num) {
        if (index < 0 || index >= arrSize)
            throw new IndexOutOfRangeException("索引越界");
        arr[index] = num;
    }

    /* 在尾部添加元素 */
    public void Add(int num) {
        // 元素数量超出容量时,触发扩容机制
        if (arrSize == arrCapacity)
            ExtendCapacity();
        arr[arrSize] = num;
        // 更新元素数量
        arrSize++;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Validate the index against the list's Count() before calling Get(): require 0 <= index < Count().
  2. Fix off-by-one loop bounds — use i < list.Count() when iterating indices.
  3. If exposing an API, clamp or reject out-of-range input at the boundary before it reaches Get().
  4. Add an assertion or precondition check in debug builds to catch invalid indices early.

Example fix

// before
int val = list.Get(i);

// after
if (i >= 0 && i < list.Count()) {
    int val = list.Get(i);
}
Defensive patterns

Strategy: validation

Validate before calling

if (index >= 0 && index < list.Count()) {
    int val = list.Get(index);
}

Type guard

bool IsValidIndex(MyList list, int i) => i >= 0 && i < list.Count();

Try / catch

try { int val = list.Get(index); }
catch (IndexOutOfRangeException) { /* invalid index */ }

Prevention

When it happens

Trigger: Calling Get(index) with index < 0 or index >= arrSize on a MyList instance. Most commonly a negative index, an index equal to arrSize (one-past-the-end), or any index computed from an off-by-one loop.

Common situations: Off-by-one errors in for-loops (e.g., iterating i <= Count() instead of i < Count()); passing a raw length as an index instead of length-1; assuming zero-based indexing end is Count() rather than Count()-1; passing user input directly as an index without validation.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/5a697c2fe1d3af33. Report an issue: GitHub.