Programming Languages
Go
Subjective
Oct 04, 2025
Explain panic, recover, and when to use them.
Detailed Explanation
Panic and Recover:
• Panic stops normal execution
• Deferred functions still run
• Recover catches panics in deferred functions
• Use for unrecoverable errors
• Prefer errors for expected failures
Example:
func safeDivide(a, b float64) (result float64, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
if b == 0 {
panic("division by zero")
}
return a / b, nil
}
When to use:
• Library initialization failures
• Impossible conditions
• Programming errors (not user errors)
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts