go / intermediate
Snippet
Managing Runtime Panics with Recover
Recover is a built-in function that regains control of a panicking goroutine. It is only useful inside deferred functions. During normal execution, a call to recover returns nil and has no other effect.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package mainimport ("fmt")func parseAndDivide(a, b int) (res int, err error) {defer func() {if r := recover(); r != nil {err = fmt.Errorf("runtime panic caught: %v", r)}}()if b == 0 {panic("division by zero is forbidden")}return a / b, nil}func main() {_, err := parseAndDivide(10, 0)fmt.Println("Handled panic gracefully:", err)}
Breakdown
1
defer func() {
Schedules a deferred function execution to clean up before the function returns.
2
if r := recover(); r != nil {
Catches any active panic in the current goroutine, returning the panic value.
3
err = fmt.Errorf(...)
Translates the panic value into a standard Go error returned to the caller.