Defer Panic Recover Pattern in Go: Explanation and Example
defer panic recover pattern in Go is a way to handle unexpected errors by deferring a function that calls recover() to catch a panic. This pattern helps keep the program running smoothly by recovering from runtime crashes and cleaning up resources.How It Works
In Go, panic is like an alarm that stops normal execution when something goes wrong, similar to a fire alarm in a building. When a panic happens, the program starts to unwind, running any deferred functions before it stops completely.
The defer panic recover pattern uses a deferred function to call recover(), which acts like a firefighter that stops the alarm and prevents the program from crashing. By placing recover() inside a deferred function, you can catch the panic and handle the error gracefully, allowing the program to continue running or exit cleanly.
Example
This example shows how to use defer, panic, and recover together to catch an error and prevent the program from crashing.
package main import "fmt" func safeDivide(a, b int) { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() if b == 0 { panic("division by zero") } fmt.Println("Result:", a/b) } func main() { safeDivide(10, 2) safeDivide(10, 0) fmt.Println("Program continues after panic recovery") }
When to Use
Use the defer panic recover pattern when you want to handle unexpected errors without crashing your whole program. It is especially useful in servers, long-running applications, or libraries where you want to catch errors, log them, and keep the program running.
For example, if a function might cause a panic due to invalid input or unexpected conditions, you can use this pattern to recover and provide a meaningful error message or fallback behavior instead of stopping the program abruptly.
Key Points
- defer schedules a function to run later, usually for cleanup.
- panic stops normal execution and starts unwinding.
- recover catches a panic inside a deferred function to prevent a crash.
- This pattern helps write safer and more robust Go programs.