panic and recover
- Version
- 1.27
- Review
- Draft
Summary#
A panic stops the current function, runs deferred calls and unwinds the goroutine. A deferred function can call recover to stop that sequence and get the panic value. Execution continues in the caller of the function that registered the recovering defer. An unrecovered panic terminates the program.
Syntax#
defer func() {
if value := recover(); value != nil {
// Report or convert the value.
}
}()
Example#
package main
import "fmt"
func divide(a, b int) (result int, err error) {
defer func() {
if value := recover(); value != nil {
err = fmt.Errorf("recovered: %v", value)
}
}()
return a / b, nil
}
func main() {
fmt.Println(divide(6, 3))
fmt.Println(divide(1, 0))
fmt.Println("still running")
}
Expected output#
2 <nil>
0 recovered: runtime error: integer divide by zero
still running
Common mistakes#
recover works when a deferred function calls it directly. A helper called by that deferred function receives nil. It also applies only to the panicking goroutine, so a parent cannot recover a panic from a goroutine it started. Return ordinary errors for expected failures.
Version applicability#
The syntax and example work from Go 1.0. In Go 1.21 and later, panic(nil) raises a *runtime.PanicNilError by default. GODEBUG=panicnil=1 restores the old behavior, in which recover could return nil during a panic. A main module declaring Go 1.20 or earlier defaults to the old behavior.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0