go runtime_error ai_generated true

panic: runtime error: index out of range [5] with length 5 (in goroutine)

ID: go/goroutine-panic-uncaught

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-08-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.23 active

Root Cause

A goroutine accesses an array or slice index that is out of bounds, causing a panic that is not recovered, crashing the entire program.

generic

中文

goroutine 访问数组或切片的越界索引,导致恐慌未被恢复,整个程序崩溃。

Workarounds

  1. 90% success Add a deferred recover inside the goroutine to handle panics gracefully
    go func() {
        defer func() {
            if r := recover(); r != nil {
                log.Printf("Recovered in goroutine: %v", r)
            }
        }()
        arr := make([]int, 5)
        arr[5] = 10 // panic here
    }()
  2. 95% success Check slice bounds before accessing
    arr := make([]int, 5)
    index := 5
    if index < len(arr) {
        arr[index] = 10
    } else {
        log.Println("Index out of bounds")
    }

Dead Ends

Common approaches that don't work:

  1. Adding recover in main but not in the goroutine 80% fail

    Panic in goroutine is not caught by main's recover unless deferred in the goroutine itself.

  2. Using a larger array but not fixing the index logic 70% fail

    Band-aid solution; index may still go out of bounds in other cases.