How to handle panics in goroutines

Prevent goroutine panics from crashing your Go program by wrapping the goroutine logic in a defer function that calls recover().

Recover from panics in goroutines by calling recover() inside a defer function within that goroutine.

func worker(id int) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("goroutine %d panicked: %v\n", id, r)
        }
    }()
    // code that might panic
    panic("oops")
}

func main() {
    for i := 0; i < 5; i++ {
        go worker(i)
    }
    time.Sleep(time.Second) // wait for goroutines
}