krahets/hello-algo · error · Error
Illegal Argument Exception
Error message
Illegal Argument Exception
What it means
Thrown by GraphAdjList.addEdge(vet1, vet2) when either vertex is absent from the adjacency list, or when vet1 === vet2 (self-loop). The method then pushes each vertex into the other's neighbor list; the guard prevents pushing into an undefined neighbor array.
Source
Thrown at zh-hant/codes/typescript/chapter_graph/graph_adjacency_list.ts:37
this.addVertex(edge[0]);
this.addVertex(edge[1]);
this.addEdge(edge[0], edge[1]);
}
}
/* 獲取頂點數量 */
size(): number {
return this.adjList.size;
}
/* 新增邊 */
addEdge(vet1: Vertex, vet2: Vertex): void {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2
) {
throw new Error('Illegal Argument Exception');
}
// 新增邊 vet1 - vet2
this.adjList.get(vet1).push(vet2);
this.adjList.get(vet2).push(vet1);
}
/* 刪除邊 */
removeEdge(vet1: Vertex, vet2: Vertex): void {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2 ||
this.adjList.get(vet1).indexOf(vet2) === -1
) {
throw new Error('Illegal Argument Exception');
}
// 刪除邊 vet1 - vet2
this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1);View on GitHub (pinned to 69932aed18)
Solutions
- Call addVertex for both endpoints before addEdge.
- Ensure vet1 and vet2 are distinct references.
- Verify graph.adjList.has(vet1) && graph.adjList.has(vet2) before addEdge.
Example fix
// before
graph.addEdge(v1, v2); // throws if vertex not registered or v1 === v2
// after
graph.addVertex(v1);
graph.addVertex(v2);
if (v1 !== v2) {
graph.addEdge(v1, v2);
} Defensive patterns
Strategy: validation
Validate before calling
// Register both vertices and ensure distinct before adding edge
graph.addVertex(v1);
graph.addVertex(v2);
if (v1 !== v2) {
graph.addEdge(v1, v2);
} Type guard
function canAddEdge(graph: GraphAdjList, v1: Vertex, v2: Vertex): boolean {
return graph.adjList.has(v1) && graph.adjList.has(v2) && v1 !== v2;
} Try / catch
try {
graph.addEdge(v1, v2);
} catch (e) {
if (e.message === 'Illegal Argument Exception') {
// vertex not registered or self-loop — handle
} else throw e;
} Prevention
- Call addVertex for both endpoints before addEdge.
- Ensure vet1 and vet2 are distinct references (no self-loops).
- Use Vertex objects from the same graph instance only.
When it happens
Trigger: Calling addEdge with a vertex not added via addVertex, or passing the same Vertex reference for both endpoints.
Common situations: Forgetting to addVertex before connecting edges; using Vertex objects from a different graph; attempting self-loops in an undirected simple graph.
Related errors
- Illegal Argument Exception
- Illegal Argument Exception
- Illegal Argument Exception
- Illegal Argument Exception
- Index Out Of Bounds Exception
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/4a3b3dffcec012b2.
Report an issue: GitHub.