Recover
suggest changeRecover attempts to recover from a panic.
The call to recover must be made directly in a deferred function. A recover in a function that the deferred function calls does not stop the panic.
recover returns the value passed to panic while the goroutine is panicking. If the goroutine is not panicking, it returns nil. Since Go 1.21, panic(nil) is recovered as a *runtime.PanicNilError, so a nil result still means there was no panic.
func foo() {
panic("bar")
}
func bar() {
defer func() {
if msg := recover(); msg != nil {
fmt.Printf("Recovered with message %s\n", msg)
}
}()
foo()
fmt.Println("Never gets executed")
}
func main() {
fmt.Println("Entering main")
bar()
fmt.Println("Exiting main the normal way")
}
Entering main
Recovered with message bar
Exiting main the normal way
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents