Panic and recover
panic stops the current goroutine and runs deferred calls as the stack unwinds. recover, called from a deferred function, catches that panic and resumes normal execution in the deferred function's caller.
Detailed Explanation
A panic is an unrecoverable moment from the current function's point of view: you hit a nil pointer, you indexed past a slice, or you called panic(err) yourself. The goroutine begins unwinding. Every defer on the way out still runs. If none of them recover, the process prints a stack and exits (or, in a test, the test fails). Other goroutines are not automatically stopped; a panic is per goroutine.
recover only works inside defer. if r := recover(); r != nil in a deferred closure catches the panic value. After recover, the function that deferred that closure returns normally. Code above it on the stack never sees the rest of its body. Recovering in main can keep a process alive; recovering in an HTTP handler keeps the server alive for the next request.
Do not use panic for ordinary errors. A bad password is an error. A JSON body you cannot parse is an error. Panic is for broken invariants ("this map should have been initialized in New") and for truly unexpected runtime faults. A library that panics on user input forces every caller to recover, which they will forget.
The panic value is any. By convention it is a string or an error. recover() returns nil when there is no panic, which is why you always check it. Re-panicking after you log (panic(r)) is correct when you are not the layer that can handle the problem; you have added a log and let the unwind continue.
http.Serve recovers. The standard library already wraps each request in a recover that logs the stack. You still want your own recover if you must translate a panic into a 500 with a request ID, or if you run workers that are not HTTP.
What it costs. Unwinding is slower than returning an error, and it discards the rest of the call stack's work. A recover in a hot path that regularly panics is a design bug. One recover at the edge of a goroutine is cheap insurance against a process-wide crash.
Code Examples
package main
import "fmt"
func safe(fn func()) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
fn()
return nil
}
func main() {
err := safe(func() { panic("boom") })
fmt.Println(err)
}func mustCompile(expr string) *Regexp {
re, err := compile(expr)
if err != nil {
panic(err) // programmer error: a static pattern is wrong
}
return re
}
type Regexp struct{}
func compile(string) (*Regexp, error) { return &Regexp{}, nil }func worker(fn func()) {
defer func() {
if r := recover(); r != nil {
fmt.Println("worker", r)
}
}()
fn()
}Common Gotchas
`recover` outside `defer` always returns nil
it does not catch a panic in the same function body unless a deferred call runs it.
Recovering in the wrong goroutine does nothing
a panic in a child goroutine will crash the process if that goroutine does not recover. HTTP's recover does not cover `go func()` you started inside the handler.
`panic(nil)` is still a panic
after Go 1.21 it is distinct from "no panic." Do not use `nil` as a sentinel panic value.
Deferred calls still run during a panic
that is why `defer mu.Unlock()` is safe. `os.Exit` is the thing that skips them.