krahets/hello-algo · error · RangeError
Index Out Of Bounds Exception
Error message
Index Out Of Bounds Exception
What it means
Thrown by GraphAdjMatrix.removeVertex(index) when index >= size(). As with the JS variant, the guard checks only the upper bound — negative indices pass through and splice treats them as offset-from-end, silently corrupting the matrix.
Source
Thrown at zh-hant/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
- Validate 0 <= index < graph.size() before removeVertex.
- Never pass negative indices — the guard does not catch them.
- Resolve positional index via vertices.indexOf(value) if you hold a value.
Example fix
// before
graph.removeVertex(index); // throws if index >= size()
// after
if (index >= 0 && index < graph.size()) {
graph.removeVertex(index);
} Defensive patterns
Strategy: validation
Validate before calling
// Full bounds check including negative index (built-in guard misses negatives)
if (index >= 0 && index < graph.size()) {
graph.removeVertex(index);
} Type guard
function isValidVertexIndex(graph: GraphAdjMatrix, index: number): boolean {
return Number.isInteger(index) && index >= 0 && index < graph.size();
} Try / catch
try {
graph.removeVertex(index);
} catch (e) {
if (e instanceof RangeError) {
// index out of bounds — handle
} else throw e;
} Prevention
- Check both bounds — the library only checks index >= size(), not index < 0.
- Use positional index, not the vertex value.
- Re-resolve indices after any removeVertex call.
When it happens
Trigger: Passing an index >= vertex count, or a negative index that bypasses the incomplete guard.
Common situations: Off-by-one after batch removals; confusing vertex value with positional index; stale size assumption after prior removes; -1 sentinel slipping past the check.
Related errors
- Index Out Of Bounds Exception
- Index Out Of Bounds Exception
- Index Out Of Bounds Exception
- Index Out Of Bounds Exception
- Index Out Of Bounds Exception
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/0774177cee53752b.
Report an issue: GitHub.