go / intermediate
Snippet
Resource Safety with Defer and Panic Recovery
The recover built-in function allows a program to regain control of a panicking goroutine. It must always be called within a deferred function to effectively catch the panic before the program exits.
snippet.go
1
2
3
4
5
6
7
8
9
10
func protectedFunction() {defer func() {if r := recover(); r != nil {fmt.Println("Recovered from panic:", r)}}()panic("something went wrong")fmt.Println("This will never run")}
Breakdown
1
defer func() { ... }()
Defines a function to be executed immediately before the function returns.
2
r := recover()
Checks if a panic is currently occurring and retrieves its value.
3
panic(...)
Triggers a runtime error that stops normal execution flow.