krahets/hello-algo · error · RangeError

Index Out Of Bounds Exception

Error message

Index Out Of Bounds Exception

What it means

Thrown by removeVertex(index) in an adjacency-matrix graph when the supplied index is greater than or equal to the current vertex count. It guards array splice operations against out-of-range indices. Note the check only tests index >= size(); a negative index passes this guard and silently splices from the end of the arrays — a latent bug.

Source

Thrown at ru/codes/typescript/chapter_graph/graph_adjacency_matrix.ts:52

        const n: number = this.size();
        // Добавить значение новой вершины в список вершин
        this.vertices.push(val);
        // Добавить строку в матрицу смежности
        const newRow: number[] = [];
        for (let j: number = 0; j < n; j++) {
            newRow.push(0);
        }
        this.adjMat.push(newRow);
        // Добавить столбец в матрицу смежности
        for (const row of this.adjMat) {
            row.push(0);
        }
    }

    /* Удаление вершины */
    removeVertex(index: number): void {
        if (index >= this.size()) {
            throw new RangeError('Index Out Of Bounds Exception');
        }
        // Удалить вершину с индексом index из списка вершин
        this.vertices.splice(index, 1);

        // Удалить строку с индексом index из матрицы смежности
        this.adjMat.splice(index, 1);
        // Удалить столбец с индексом index из матрицы смежности
        for (const row of this.adjMat) {
            row.splice(index, 1);
        }
    }

    /* Добавление ребра */
    // Параметры i и j соответствуют индексам элементов vertices
    addEdge(i: number, j: number): void {
        // Обработка выхода индекса за границы и случая равенства
        if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
            throw new RangeError('Index Out Of Bounds Exception');

View on GitHub (pinned to 69932aed18)

Solutions

  1. Recompute the index from the current vertices array immediately before calling removeVertex (e.g. vertices.indexOf(val)).
  2. Add a negative-index guard in the method: if (index < 0 || index >= this.size()) throw ...
  3. Validate against graph.size() before the call.
  4. Prefer value-based lookups over stored indices when vertices are removed frequently.

Example fix

// before (method has a negative-index hole)
removeVertex(index: number): void {
    if (index >= this.size()) {
        throw new RangeError('Index Out Of Bounds Exception');
    }
    ...
}

// after
removeVertex(index: number): void {
    if (index < 0 || index >= this.size()) {
        throw new RangeError('Index Out Of Bounds Exception');
    }
    ...
}
Defensive patterns

Strategy: validation

Validate before calling

if (index >= 0 && index < graph.size()) {
    graph.removeVertex(index);
}

Type guard

function isValidVertexIndex(graph: GraphAdjMat, index: number): boolean {
    return Number.isInteger(index) && index >= 0 && index < graph.size();
}

Try / catch

try {
    graph.removeVertex(index);
} catch (e) {
    if (e instanceof RangeError && e.message === 'Index Out Of Bounds Exception') {
        // handle stale/invalid index
    } else throw e;
}

Prevention

When it happens

Trigger: Calling removeVertex with an index >= vertices.length after prior removals shifted the count, or passing an index obtained from stale state. Also any negative index slips past the guard but corrupts data rather than throwing.

Common situations: Using a cached index that became stale after an earlier removeVertex shifted subsequent indices; off-by-one loops that reach size(); forgetting that removal re-indexes all higher vertices.

Related errors


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