Go by Example: Panic and Recover
Understand Panic and Recover, Go's mechanism for handling exceptional, unrecoverable errors. This example shows how to trigger a panic and how to use `defer` and `recover` to gracefully regain control of a panicking goroutine.
Code
package main
import "fmt"
func main() {
// Defer a function to handle the panic
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered. Error:
", r)
}
}()
fmt.Println("Calling panic...")
mayPanic()
fmt.Println("After panic (this won't run)")
}
func mayPanic() {
panic("a problem")
}
Explanation
A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn't occur during normal operation, or that we aren't prepared to handle gracefully.
Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.
When to use panic/recover:
- For truly unrecoverable errors (e.g., corrupted config)
- Inside libraries to catch internal errors but return standard errors to users
- Rarely for normal control flow (use error return values instead)

