Go Reference ยท Built-in Functions
Go recover() function
Reference for Go recover(): stop a panic from inside a deferred function, get the panic value, convert it to an error, and the rules for where it works.
recover() stops a panic and returns the value that was passed to panic(). It only has an effect when it is called directly by a deferred function while the goroutine is panicking. Called anywhere else, it returns nil and does nothing.
When a panic is recovered, the function that deferred the call returns to its caller normally. The code that was running when the panic happened does not continue; Go has no "resume" after a panic. The usual pattern is to turn the panic into an error return.
func safe(f func()) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("recovered: %v", r) } }() f() return nil }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func recover() any
Returns: the argument given to panic() if the goroutine is panicking and recover is called directly by a deferred function; otherwise nil.
Edge cases:
- Since Go 1.21,
panic(nil)produces a*runtime.PanicNilError, sorecover() != nilis reliable. With//go:debug panicnil=1it returnsnil. - Calling
recoverin a nested function called by the deferred function returnsnil. runtime.Goexit()is not a panic;recoverreturnsnilfor it.
Usage notes
- Must be inside
defer. Writingrecover()in normal code has no effect. Wrap the code that may panic in a function with a deferred closure. - Set named results (
err, as in the examples) from the deferred closure to return a value; unnamed results come back as zero values. - Recover where you can act. Typical places are the edge of a goroutine, a worker loop, or a request handler. Do not sprinkle recovery through ordinary code, which hides bugs.
- Check the value. Use a type switch or
runtime.Errorcheck; re-panic withpanic(r)if it is something you did not expect, so real bugs still surface. - Stack traces:
runtime/debug.Stack()called inside the deferred function gives the trace of the panic site, useful for logging. - Goroutines: a panic in a goroutine you started must be recovered inside that goroutine; the caller cannot catch it.
- State may be inconsistent after a panic (half-updated structures, held locks). Recovering does not repair that.
Related
panic(),defer, Panic and recover rules,go- Lessons: Panic and recover, Defer