{"record":{"id":"9630693c05a42158","repo":"krahets/hello-algo","slug":"index-out-of-bounds-exception-963069","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/javascript/chapter_graph/graph_adjacency_matrix.js","lineNumber":52,"sourceCode":"        const n = this.size();\n        // Добавить значение новой вершины в список вершин\n        this.vertices.push(val);\n        // Добавить строку в матрицу смежности\n        const newRow = [];\n        for (let j = 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) {\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, j) {\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/javascript/chapter_graph/graph_adjacency_matrix.js#L34-L70","documentation":"Thrown by GraphAdjacencyMatrix.removeVertex (JS) as a RangeError when the index argument is out of range. It splices both the vertex row and its matrix column, so an invalid index would desync vertices and adjMat. NOTE: the guard only checks index >= size(); a negative index passes the check and produces silent corruption rather than this error.","triggerScenarios":"removeVertex(index) called with index >= this.size() (e.g., size 5 and index 5). A negative index does NOT trigger this error — it slips through and corrupts the matrix.","commonSituations":"Off-by-one after addVertex/removeVertex shifts indices; stale cached index into a matrix whose size changed; iterating vertices.length without accounting for a prior removal.","solutions":["Validate bounds yourself including negatives: if (index >= 0 && index < g.size()) g.removeVertex(index).","Re-fetch size() immediately before the call rather than caching it.","Prefer looking up the vertex by value rather than by shifting index when possible.","Report the missing negative-index guard upstream as a bug."],"exampleFix":"// before\ng.removeVertex(idx); // throws RangeError when idx >= size\n\n// after\nif (idx >= 0 && idx < g.size()) g.removeVertex(idx);\nelse throw new RangeError('bad vertex index: ' + idx);","handlingStrategy":"validation","validationCode":"// NOTE: the library only checks index >= size; you must also reject negatives\nif (index >= 0 && index < g.size()) g.removeVertex(index);\nelse throw new RangeError('Invalid vertex index: ' + index);","typeGuard":"function isValidVertexIndex(index, g) {\n  return Number.isInteger(index) && index >= 0 && index < g.size();\n}","tryCatchPattern":null,"preventionTips":["Never cache vertex indices across add/remove operations — refetch size() each time.","Reject negative indices yourself; the library guard is incomplete.","Prefer value-based lookup over positional indexing where the API allows."],"tags":["graph","javascript","precondition","range","hello-algo","off-by-one"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}