Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Concepts

Panic and recover rules in Go

The exact rules for Go panic and recover: where recover works, how deferred calls run, re-panicking, goroutine boundaries, and when a panic is appropriate.

A panic stops normal execution of the current goroutine. Deferred calls run as the stack unwinds, and if nothing recovers, the program prints the panic value with a stack trace and exits with status 2. The built-in recover stops the unwinding, but only in narrow circumstances.

Go's convention is that expected failures are returned as errors and panics are for programmer mistakes and impossible states. This page lists the precise rules so you can use recover correctly and know when not to.

Go
defer func() {
    if r := recover(); r != nil {
        fmt.Println("recovered:", r)
    }
}()

Try it

Go Where recover works

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.

Go Turning a panic into an error

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.

The rules

  • recover returns a non-nil value only when it is called directly by a deferred function while the goroutine is panicking. Called anywhere else (even in a helper that the deferred function calls), it returns nil.
  • A recovered panic ends the unwinding. The function that deferred the recovering call returns normally to its caller, with its named results as they are at that moment.
  • Panics do not cross goroutines. A panic in one goroutine that is not recovered in that goroutine terminates the whole program. A recover in main will not catch it.
  • panic(v) accepts any value. Since Go 1.18 panic(nil) is turned into a *runtime.PanicNilError, so recover() returning nil reliably means "not panicking" (the //go:debug panicnil=1 setting restores the old behavior).
  • Runtime panics (nil dereference, index out of range, division by zero, failed type assertion) carry a value that implements runtime.Error.
  • If a deferred function panics while another panic is in flight, the new panic replaces the old one as the current panic (the trace still lists both).

When to panic

  • Impossible situations and violated invariants (the equivalent of an assertion).
  • Failures during program initialization where continuing makes no sense (regexp.MustCompile, template.Must).
  • Inside a package, as an internal shortcut to escape deep recursion, as long as it is recovered at the public API boundary and returned as an error. Never let it escape to callers.

When to recover

  • At boundaries that must stay alive: an HTTP server already recovers per request; a worker pool may recover per job and log the stack with debug.Stack().
  • Never to hide bugs. A recovered panic that is silently ignored makes a broken program look healthy.

Usage notes

  • os.Exit and log.Fatal do not run deferred functions and are not panics.
  • runtime.Goexit runs deferred calls but is not a panic; recover returns nil during it.
  • Re-panic with panic(r) after logging when you cannot handle the value.