krahets/hello-algo · error
error
Error message
error
What it means
Panic thrown by addEdge(vet1, vet2) on the undirected adjacency-list graph (Traditional Chinese build) when the edge is illegal: an endpoint vertex is not in the adjacency map, or vet1 == vet2 (no self-loops). The graph only connects two distinct, already-registered vertices, so it aborts with 'error' otherwise.
Source
Thrown at zh-hant/codes/go/chapter_graph/graph_adjacency_list.go:45
for _, edge := range edges {
g.addVertex(edge[0])
g.addVertex(edge[1])
g.addEdge(edge[0], edge[1])
}
return g
}
/* 獲取頂點數量 */
func (g *graphAdjList) size() int {
return len(g.adjList)
}
/* 新增邊 */
func (g *graphAdjList) addEdge(vet1 Vertex, vet2 Vertex) {
_, ok1 := g.adjList[vet1]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// 新增邊 vet1 - vet2, 新增匿名 struct{},
g.adjList[vet1] = append(g.adjList[vet1], vet2)
g.adjList[vet2] = append(g.adjList[vet2], vet1)
}
/* 刪除邊 */
func (g *graphAdjList) removeEdge(vet1 Vertex, vet2 Vertex) {
_, ok1 := g.adjList[vet1]
_, ok2 := g.adjList[vet2]
if !ok1 || !ok2 || vet1 == vet2 {
panic("error")
}
// 刪除邊 vet1 - vet2
g.adjList[vet1] = DeleteSliceElms(g.adjList[vet1], vet2)
g.adjList[vet2] = DeleteSliceElms(g.adjList[vet2], vet1)
}
View on GitHub (pinned to 69932aed18)
Solutions
- Register both endpoints via addVertex() before addEdge().
- Guard: ensure vet1 != vet2 and both vertices are present in the map.
- Two-pass graph construction: collect distinct vertices, add them, then add edges.
- Drop or log edges referencing unknown/duplicate vertices instead of panicking.
Example fix
// before: panics on missing vertex or self-loop
g.addEdge(a, b)
// after
if a != b {
g.addVertex(a); g.addVertex(b)
g.addEdge(a, b)
} Defensive patterns
Strategy: validation
Validate before calling
if vet1 != vet2 && g.hasVertex(vet1) && g.hasVertex(vet2) {
g.addEdge(vet1, vet2)
} Try / catch
defer func() {
if r := recover(); r != nil {
// addEdge rejected
}
}()
g.addEdge(vet1, vet2) Prevention
- Register all distinct vertices before adding any edge.
- Filter out self-loops (vet1 == vet2) before calling addEdge().
- Use two-pass construction: vertices first, edges second.
When it happens
Trigger: addEdge() before both addVertex() calls; vet1 == vet2; referencing a vertex removed by removeVertex().
Common situations: Loading an edge list without first extracting/registering the vertex set; assuming the graph constructor created vertices it actually skipped; pipeline that deletes a vertex then re-adds an edge touching it.
Related errors
- error
- Illegal Argument Exception
- Illegal Argument Exception
- Illegal Argument Exception
- Illegal Argument Exception
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/28803473b53d40bb.
Report an issue: GitHub.