Recover Goroutine Panics Inside The Worker
A panic in a goroutine kills the whole process unless that same goroutine recovers; workers report failures through a channel instead of crashing main.
Code
package main
import "fmt"
// recover 必须写在 panic 源头所在的 goroutine 内:
// 主 goroutine 的 defer 接不到其他 goroutine 抛出的 panic
func worker(id int, out chan<- string) {
defer func() {
if r := recover(); r != nil {
out <- fmt.Sprintf("task %d recovered: %v", id, r)
}
}()
if id%2 == 1 {
panic("bad index")
}
out <- fmt.Sprintf("task %d finished", id)
}
func main() {
out := make(chan string, 1)
go worker(0, out)
fmt.Println(<-out)
go worker(1, out)
fmt.Println(<-out)
// 没有 recover 的 goroutine panic 会直接终止整个进程,无法在别处捕获
fmt.Println("process still alive")
}How it works
Recover Goroutine Panics Inside The Worker keeps everything in the functions worker and main.
Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Putting it to use
The primary signature, spelled out, is func worker(id int, out chan<- string)
The demo output is labeled (process still alive), so each line traces straight back to the statement that printed it.
Running the file executes main, which drives worker in order.
The core lines of the flow
func worker(id int, out chan<- string) {
defer func() {
if r := recover(); r != nil {
out <- fmt.Sprintf("task %d recovered: %v", id, r)
}
}()
if id%2 == 1 {
panic("bad index")
}
out <- fmt.Sprintf("task %d finished", id)
}
func main() {
out := make(chan string, 1)
go worker(0, out)
fmt.Println(<-out)
go worker(1, out)
fmt.Println(<-out)
// 没有 recover 的 goroutine panic 会直接终止整个进程,无法在别处捕获
fmt.Println("process still alive")
}
Interactive Tools for This Topic
FAQ
- What does Recover Goroutine Panics Inside The Worker print when run?
- No setup needed: run the file and look for labeled lines like `process still alive` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.