How to Use Panic and Recover in Go: Simple Guide
In Go, use
panic to stop normal execution when a serious error occurs, and recover inside a deferred function to regain control and handle the error gracefully. This combination helps prevent your program from crashing unexpectedly.Syntax
panic stops the normal flow and starts panicking with a value, usually an error message.
recover is used inside a deferred function to catch the panic and resume normal execution.
Use defer to ensure recover runs when a panic happens.
go
func main() {
defer func() {
if r := recover(); r != nil {
println("Recovered from panic:", r)
}
}()
panic("something went wrong")
}Output
Recovered from panic: something went wrong
Example
This example shows how panic stops the program and recover catches the panic to prevent the program from crashing.
go
package main import "fmt" func safeDivide(a, b int) int { defer func() { if r := recover(); r != nil { fmt.Println("Recovered in safeDivide:", r) } }() if b == 0 { panic("division by zero") } return a / b } func main() { fmt.Println("Result:", safeDivide(10, 2)) fmt.Println("Result:", safeDivide(10, 0)) fmt.Println("Program continues...") }
Output
Result: 5
Recovered in safeDivide: division by zero
Result: 0
Program continues...
Common Pitfalls
- Calling
recoveroutside a deferred function does nothing. - If you don't use
defer,recoverwon't catch the panic. - Overusing
panicfor normal errors is bad practice; use error returns instead.
go
package main import "fmt" func wrongRecover() { r := recover() // This won't catch panic because it's not deferred fmt.Println("Recover called outside defer, got:", r) } func main() { wrongRecover() panic("panic without defer recover") }
Quick Reference
Panic: Use to stop execution on serious errors.
Recover: Use inside defer to catch panic and continue.
Defer: Ensures recover runs after panic.
| Function | Purpose | Usage |
|---|---|---|
| panic | Stops normal execution and starts panic | panic("error message") |
| recover | Catches panic inside deferred function | defer func() { if r := recover(); r != nil { /* handle */ } }() |
| defer | Delays function execution until surrounding function returns | defer func() { /* code */ }() |
Key Takeaways
Use panic to stop execution when a serious error occurs.
Use recover inside a deferred function to catch and handle panics.
Always call recover within defer to successfully catch panics.
Avoid using panic for normal error handling; prefer error returns.
Recover lets your program continue running after a panic.