go / intermediate
Snippet
Safely Handling Unexpected Runtime Panics
In Go, panics can disrupt program execution. Using `recover` inside a deferred function allows the application to capture the panic, convert it into a standard error, and prevent the application from crashing.
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
23
24
25
package mainimport ("fmt""log")func safeDivide(a, b int) (result int, err error) {defer func() {if r := recover(); r != nil {err = fmt.Errorf("recovered from panic: %v", r)}}()result = a / breturn result, nil}func main() {res, err := safeDivide(10, 0)if err != nil {log.Printf("Error: %v", err)} else {log.Printf("Result: %d", res)}}
Breakdown
1
defer func() {
Defers the execution of the anonymous function until safeDivide returns.
2
if r := recover(); r != nil {
Checks if a panic occurred during the function execution and captures its value.
3
err = fmt.Errorf("recovered from panic: %v", r)
Converts the panic into a standard error and assigns it to the named return parameter.
4
result = a / b
Performs division, which will trigger a division-by-zero runtime panic if b is 0.