midGolang
Explain Panic and Recover in Go.
Updated Apr 28, 2026
Short answer
panic halts normal execution, while recover regains control of a panicking goroutine.
Deep explanation
When panic is called, deferred functions are executed, and then the program crashes. recover is a built-in function that must be called inside a deferred function. It intercepts the panic, stops the crashing sequence, and allows normal execution to resume.
Real-world example
Preventing a web server from crashing completely if a single HTTP handler hits a nil pointer dereference.
Common mistakes
- Using panic/recover for normal control flow or validation errors. Go idiom dictates using standard `error` return values for expected failure conditions.
Follow-up questions
- Can `recover` catch a panic in a different goroutine?