Go by Example: Panic and Recover
Handle unexpected errors and prevent program crashes. This example shows how to trigger a panic and use `recover()` within a deferred function to regain control and handle the error gracefully.
Code
package main
import "fmt"
func main() {
// Recover must be called within a deferred function
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered. Error:", r)
}
}()
mayPanic()
// This code will not run because mayPanic panics
fmt.Println("After mayPanic()")
}
func mayPanic() {
fmt.Println("About to panic")
panic("a problem")
}Explanation
A panic in Go is similar to an exception in other languages: it stops the ordinary flow of control and begins unwinding the stack. When a function panics, its execution stops, any deferred functions are executed, and then the panic propagates up to its caller. This continues until the program crashes with a stack trace or the panic is handled by recover.
recover is a built-in function that regains control of a panicking goroutine. It is only useful inside deferred functions. During normal execution, recover returns nil and does nothing. If the current goroutine is panicking, recover captures the value passed to panic and resumes normal execution from that point (the function where defer was called returns normally).
Best practices:
- Use
paniconly for unrecoverable errors (e.g., programmer errors, invalid state) that simply shouldn't happen. - Use
errorreturn values for expected error conditions (e.g., file not found, network timeout). - Always check if
recover()returns non-nil to verify a panic actually occurred.

