Unrecovered Goroutine Panics Crash The Process
Show that a panic in one goroutine crashes the whole process, and demonstrate the recover-in-worker pattern that contains it.
Code
package main
import "fmt"
func risky(id int, fail bool) (result int) {
defer func() {
// 在 worker 内 recover,把 panic 转成错误返回值
if r := recover(); r != nil {
fmt.Printf("worker %d recovered: %v\n", id, r)
result = -1
}
}()
if fail {
panic("bad input")
}
return id * 10
}
func main() {
fmt.Println("safe worker:", risky(1, false))
fmt.Println("failing worker:", risky(2, true))
// 未 recover 的 panic 会击穿整个进程,而不是只杀当前 goroutine:
// go func() { panic("unrecovered") }() 会让 main 无法继续。
fmt.Println("process survived both workers")
}The working sequence
Everything happens inside the functions risky and main.
Cleanup is attached with defer, so it runs on every exit path of the function.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The primary signature is func risky(id int, fail bool) (result int)
The printed lines carry step labels — worker, safe worker:, failing worker: — when the file runs.
The demo flow inside main is risky — run the file to see it end to end.
Key statements
if r := recover(); r != nil {
fmt.Printf("worker %d recovered: %v\n", id, r)
result = -1
}
func main() {
fmt.Println("safe worker:", risky(1, false))
fmt.Println("failing worker:", risky(2, true))
// 未 recover 的 panic 会击穿整个进程,而不是只杀当前 goroutine:
// go func() { panic("unrecovered") }() 会让 main 无法继续。
fmt.Println("process survived both workers")
}
panic("bad input")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Unrecovered Goroutine Panics Crash The Process print when run?
- Running the file directly is enough — expect labeled output lines such as `worker`, `safe worker:`, `failing worker:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.