{"record":{"id":"4e8621bdc3e9ca82","repo":"krahets/hello-algo","slug":"index-out-of-bounds-exception-4e8621","errorCode":null,"errorMessage":"Index Out Of Bounds Exception","messagePattern":"Index Out Of Bounds Exception","errorType":"exception","errorClass":"RangeError","httpStatus":null,"severity":"error","filePath":"ru/codes/typescript/chapter_graph/graph_adjacency_matrix.ts","lineNumber":52,"sourceCode":"        const n: number = this.size();\n        // Добавить значение новой вершины в список вершин\n        this.vertices.push(val);\n        // Добавить строку в матрицу смежности\n        const newRow: number[] = [];\n        for (let j: number = 0; j < n; j++) {\n            newRow.push(0);\n        }\n        this.adjMat.push(newRow);\n        // Добавить столбец в матрицу смежности\n        for (const row of this.adjMat) {\n            row.push(0);\n        }\n    }\n\n    /* Удаление вершины */\n    removeVertex(index: number): void {\n        if (index >= this.size()) {\n            throw new RangeError('Index Out Of Bounds Exception');\n        }\n        // Удалить вершину с индексом index из списка вершин\n        this.vertices.splice(index, 1);\n\n        // Удалить строку с индексом index из матрицы смежности\n        this.adjMat.splice(index, 1);\n        // Удалить столбец с индексом index из матрицы смежности\n        for (const row of this.adjMat) {\n            row.splice(index, 1);\n        }\n    }\n\n    /* Добавление ребра */\n    // Параметры i и j соответствуют индексам элементов vertices\n    addEdge(i: number, j: number): void {\n        // Обработка выхода индекса за границы и случая равенства\n        if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {\n            throw new RangeError('Index Out Of Bounds Exception');","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/ru/codes/typescript/chapter_graph/graph_adjacency_matrix.ts#L34-L70","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Recompute the index from the current vertices array immediately before calling removeVertex (e.g. vertices.indexOf(val)).","Add a negative-index guard in the method: if (index < 0 || index >= this.size()) throw ...","Validate against graph.size() before the call.","Prefer value-based lookups over stored indices when vertices are removed frequently."],"exampleFix":"// before (method has a negative-index hole)\nremoveVertex(index: number): void {\n    if (index >= this.size()) {\n        throw new RangeError('Index Out Of Bounds Exception');\n    }\n    ...\n}\n\n// after\nremoveVertex(index: number): void {\n    if (index < 0 || index >= this.size()) {\n        throw new RangeError('Index Out Of Bounds Exception');\n    }\n    ...\n}","handlingStrategy":"validation","validationCode":"if (index >= 0 && index < graph.size()) {\n    graph.removeVertex(index);\n}","typeGuard":"function isValidVertexIndex(graph: GraphAdjMat, index: number): boolean {\n    return Number.isInteger(index) && index >= 0 && index < graph.size();\n}","tryCatchPattern":"try {\n    graph.removeVertex(index);\n} catch (e) {\n    if (e instanceof RangeError && e.message === 'Index Out Of Bounds Exception') {\n        // handle stale/invalid index\n    } else throw e;\n}","preventionTips":["Recompute indices from the live vertices array right before removal.","Remember removeVertex shifts all higher indices down by one.","Add a negative-index check in the method to close the silent-splice hole."],"tags":["graph","adjacency-matrix","typescript","index-out-of-bounds","boundary-check","negative-index-bug"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}