Panic & Recover: The Last Resort

Panic & Recover: The Last Resort in Go: Every station on a production line has an emergency stop.

The Analogy: The Emergency Stop Button

Every station on a production line has an emergency stop. Hitting it does not politely return a status code to the next station -- it halts this line immediately and starts an orderly shutdown backwards along it, station by station, each one running its own shutdown checklist as the stop propagates. That is panic: normal execution of the current goroutine stops dead, and the runtime walks back up the call stack running every deferred function it finds, in reverse order, before the process finally reports what happened and dies with exit status 2.

recover is the one supervisor with the authority to cancel the alarm. The catch -- and it is the detail everyone gets wrong first -- is that the supervisor must already be standing at their station with the checklist in hand. recover() only does anything when it is called directly by a deferred function of a frame that is currently unwinding. Call it at the top of a normal function and it returns nil and does nothing at all. Call it from a helper that your deferred function calls, and it also returns nil.

If nobody cancels the alarm, the whole plant stops, and this is the part people underestimate: a panic in any goroutine kills the entire process, not just that goroutine. There is no supervisor on another line who can reach across. A goroutine that runs work you do not fully trust needs its own defer/recover at its own top level, or one bad input takes down the server.

Where the analogy stops: an emergency stop is always deliberate, and most Go panics are not. Dereferencing a nil pointer, indexing past the end of a slice, dividing by zero, sending on a closed channel, or a failed type assertion all raise a panic that looks identical to one you wrote by hand -- they arrive as a runtime.Error. Some failures are worse than a panic and cannot be recovered at all: a concurrent map write, a whole-program deadlock, or stack exhaustion print fatal error: and terminate immediately, deferred functions and recover notwithstanding.


Syntax or Core Structure

package main

import (
	"errors"
	"fmt"
)

// Named results are what let a deferred function change what is returned.
func safeDivide(a, b int) (q int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

func notRecovering() string {
	defer fmt.Println("defer runs on the normal path too")
	if r := recover(); r != nil { // not deferred: always nil
		return "impossible"
	}
	return "no panic in progress"
}

type ValidationError struct{ Field string }

func (e ValidationError) Error() string { return "invalid " + e.Field }

func mustValidate(name string) {
	if name == "" {
		panic(ValidationError{Field: "name"}) // panic with a typed value
	}
}

func typedRecover(name string) (err error) {
	defer func() {
		r := recover()
		if r == nil {
			return
		}
		if ve, ok := r.(ValidationError); ok {
			err = ve // a panic we understand becomes an ordinary error
			return
		}
		panic(r) // anything else is not ours: put it back
	}()
	mustValidate(name)
	return nil
}

func main() {
	fmt.Println(safeDivide(10, 2))
	fmt.Println(safeDivide(1, 0))

	fmt.Println(notRecovering())

	err := typedRecover("")
	var ve ValidationError
	fmt.Println("err:", err, "isValidation:", errors.As(err, &ve))

	fmt.Println("still running")
}

Output:

5 <nil>
0 recovered: runtime error: integer divide by zero
defer runs on the normal path too
no panic in progress
err: invalid name isValidation: true
still running

Note that safeDivide(1, 0) returns 0 for q: the return a / b, nil statement never completed, so the named result kept its zero value while the deferred function set err. Note too that notRecovering's recover() returned nil even though it compiles perfectly -- there is no warning for this, which is why the deferred-closure form is the only one worth memorising.


Technical Depth: Unwinding, Precisely

What panic(v) does, in order

  1. Stops executing the current function.
  2. Runs the deferred functions of the current frame, then of its caller, then its caller's caller -- LIFO, one frame at a time. A deferred function may itself panic, which replaces the value being propagated.
  3. If some deferred function calls recover(), propagation stops there. Execution resumes after that deferred function's frame returns, meaning the recovering function returns normally with whatever its results now hold.
  4. Otherwise, when the goroutine's stack is exhausted, the runtime prints panic: plus the value, plus goroutine N [running]: and a stack trace, then exits with status 2.

When recover() returns nil

SituationResult
Called in a deferred function while that frame is unwindingThe panic value; propagation stops
Called in a deferred function with no panic in flightnil
Called directly in a normal (non-deferred) function bodynil
Called from a function invoked by the deferred functionnil -- it must be the deferred call itself
Called in a different goroutine from the panicnil; the process still dies

That fourth row is subtle: defer cleanup() where cleanup calls recover() does work (cleanup is the deferred function), but defer func(){ helper() }() where helper calls recover() does not.

The panic value is any

You may panic with anything. The conventions worth following:

  • Panic with an error or a custom type, so a recovering layer can use a type assertion rather than parse a string.
  • Runtime panics carry a value implementing runtime.Error (which implements error), so if re, ok := r.(runtime.Error); ok distinguishes "the language caught a bug" from "someone signalled deliberately".
  • Since Go 1.21, panic(nil) panics with a *runtime.PanicNilError instead of a nil value, so recover() != nil is now reliable. Older code sometimes relied on the old behaviour; do not.

Converting a panic into an error, and back

The idiom in typedRecover above is the whole pattern: recover, type-assert for the panics you own, turn those into errors, and panic(r) anything else. Swallowing unknown panics is how a nil-pointer bug becomes a silent wrong answer. A re-panic shows in the trace as panic: X [recovered] followed by the new panic, so the original site is still visible.

What cannot be recovered

FailureWhy recover cannot help
fatal error: concurrent map writesThe runtime detected memory corruption in progress and stops immediately.
fatal error: all goroutines are asleep - deadlock!Nothing is running, so no deferred function can execute.
Stack exhaustion (goroutine stack exceeds ...)There is no stack left to run a handler on.
Out of memorySame.
os.Exit(n)Not a panic: it exits without running a single deferred function.

GOTRACEBACK controls how much you see on the way out: none, single (the default -- just the panicking goroutine), all, system, crash. Setting GOTRACEBACK=all when reproducing a concurrency bug is often the fastest step available.

Panics do not cross goroutines

go func() {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("worker: recovered: %v", r)
		}
	}()
	handle(job) // whatever this does, the server survives
}()

A recover in main cannot save a panicking goroutine. Every goroutine that runs user input, plugin code, or anything you did not write needs its own recovery at its own top. This is exactly what net/http does per request: the server recovers, logs, closes the connection, and keeps serving -- and http.ErrAbortHandler is the sentinel you panic with when you want that machinery to stay quiet.

When a panic is the right answer

  • Impossible state / programmer error. A default: branch on your own exhaustive enum, or an invariant that can only break if the code is wrong. An error return would just be noise the caller cannot act on.
  • Must constructors at init time. regexp.MustCompile, template.Must -- the input is a literal in your source, so a failure is a compile-time-ish bug and dying at startup is correct. Only name a function MustX if the non-panicking X also exists.
  • Deep recursion inside one package. A recursive-descent parser threading error through nine levels is mostly plumbing; panicking internally and recovering at the exported boundary is idiomatic provided the panic never escapes the package. That is the next section.

Everything else returns an error. "The user typed something wrong" is never a panic.


Real World Example: A Recursive Parser That Panics Inward and Returns Outward

Six mutually recursive methods, none of which returns an error, and one exported function that never panics. This is the sanctioned use of panic: an internal control-flow shortcut with a hard boundary.

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// Unexported: this type must never escape the package.
type parseError struct {
	pos int
	msg string
}

type parser struct {
	toks []string
	pos  int
}

func (p *parser) fail(format string, args ...any) {
	panic(parseError{pos: p.pos, msg: fmt.Sprintf(format, args...)})
}

func (p *parser) peek() string {
	if p.pos >= len(p.toks) {
		return ""
	}
	return p.toks[p.pos]
}

func (p *parser) next() string {
	t := p.peek()
	p.pos++
	return t
}

// expr := term (("+" | "-") term)*
func (p *parser) expr() int {
	v := p.term()
	for {
		switch p.peek() {
		case "+":
			p.next()
			v += p.term()
		case "-":
			p.next()
			v -= p.term()
		default:
			return v
		}
	}
}

// term := factor (("*" | "/") factor)*
func (p *parser) term() int {
	v := p.factor()
	for {
		switch p.peek() {
		case "*":
			p.next()
			v *= p.factor()
		case "/":
			p.next()
			d := p.factor()
			if d == 0 {
				p.fail("division by zero") // four frames deep, no error return
			}
			v /= d
		default:
			return v
		}
	}
}

// factor := number | "(" expr ")"
func (p *parser) factor() int {
	t := p.next()
	if t == "(" {
		v := p.expr()
		if got := p.next(); got != ")" {
			p.fail("want ), got %q", got)
		}
		return v
	}
	n, err := strconv.Atoi(t)
	if err != nil {
		p.fail("want a number, got %q", t)
	}
	return n
}

// The only exported function, and the only recover in the package.
func Eval(input string) (n int, err error) {
	defer func() {
		r := recover()
		if r == nil {
			return
		}
		pe, ok := r.(parseError)
		if !ok {
			panic(r) // not ours: a genuine bug, let it kill the process
		}
		err = fmt.Errorf("%s: token %d: %s", input, pe.pos, pe.msg)
	}()

	p := &parser{toks: strings.Fields(input)}
	n = p.expr()
	if p.pos != len(p.toks) {
		p.fail("unexpected %q", p.peek())
	}
	return n, nil
}

func main() {
	for _, in := range []string{
		"2 + 3 * 4",
		"( 2 + 3 ) * 4",
		"10 / 0",
		"1 +",
		"( 1 + 2",
		"7 7",
	} {
		n, err := Eval(in)
		if err != nil {
			fmt.Println("error:", err)
			continue
		}
		fmt.Printf("%-12s = %d\n", in, n)
	}
}

Output:

2 + 3 * 4    = 14
( 2 + 3 ) * 4 = 20
error: 10 / 0: token 3: division by zero
error: 1 +: token 3: want a number, got ""
error: ( 1 + 2: token 5: want ), got ""
error: 7 7: token 1: unexpected "7"

Count the error returns in the grammar: zero. expr, term and factor return int, which is what makes v += p.term() and v *= p.factor() readable as arithmetic rather than as plumbing. Written with (int, error) every one of those lines becomes three, and the grammar disappears into error checks that all do the same thing -- abandon everything and return. When the only possible response to a failure is "give up entirely", a panic is expressing exactly that, and it is expressing it once instead of at nine call sites.

The boundary is what makes this legitimate, and it has three parts. parseError is unexported, so no caller can even name the type; Eval is the only exported function; and Eval's deferred closure type-asserts for parseError and re-panics anything else. That last line is the load-bearing one -- without it, a nil-map write or an off-by-one index somewhere in factor would be silently converted into a "parse error" and the real bug would be invisible. Recovering selectively is the difference between this pattern and swallowing failures.

All six results are deterministic, including the failures, because the position is data. p.pos at the moment of the panic identifies the token, so 10 / 0 reports token 3 and ( 1 + 2 reports token 5 -- the point where a ) was demanded and end-of-input was found instead. Carrying the position in the panic value rather than formatting a message at the panic site is what lets Eval add the input string as context afterwards, in one place.

Eval panics too, on its own last line. After p.expr() returns, 7 7 has consumed only one token, so Eval calls p.fail itself -- and its own deferred function recovers that, because a frame's defers run when that frame unwinds regardless of where in it the panic started. Note that n was already 7 when the panic fired: a recovered function returns whatever its named results hold, so a caller must trust err and ignore n. That is why the doc convention "on error, the other results are unspecified" exists.


Common Mistakes

  1. Calling recover() outside a deferred function. It returns nil and the panic continues. There is no warning, and the code looks reasonable.
  2. Calling recover() from a helper that the deferred function calls. Also nil. It must be the deferred call itself: defer func() { r := recover(); ... }().
  3. Recovering without named return values. The deferred closure has nothing to assign to, so the function returns its zero values and the caller sees success.
  4. Recovering everything. if recover() != nil { return } turns nil-pointer bugs into silent wrong answers. Assert for the panics you own and panic(r) the rest.
  5. Expecting a recover in main to save a panicking goroutine. It cannot. Each goroutine needs its own, or the process dies.
  6. Using panic for expected failures. Bad user input, a missing file, a failed request -- all errors. Reserve panic for "this code is wrong".
  7. Letting a panic type escape the package. If callers must type-assert your panic value, you have built an exception hierarchy with worse ergonomics. Convert at the boundary.
  8. Assuming recover catches fatal error:. Concurrent map writes, whole-program deadlock and stack exhaustion are not panics and cannot be intercepted.
  9. Using os.Exit in a function with deferred cleanup. It runs no defers at all -- no flush, no unlock, no temp-file removal.
  10. Naming something MustX when no X exists. The Must prefix is a promise that a non-panicking version is available; without it, callers have no escape.
  11. Panicking inside a deferred function during unwinding. It replaces the original panic value, and the first failure -- usually the interesting one -- is lost from the message.

Best Practices

  • Default to returning errors. Reach for panic only for impossible states, Must helpers, and package-internal recursion.
  • Write the recovery as defer func() { ... }() with named results, and put it at the exported boundary.
  • Type-assert the recovered value and re-panic anything you do not recognise.
  • Keep panic values typed and unexported, so the pattern cannot leak into your API.
  • Give every long-lived or input-driven goroutine its own defer/recover top level.
  • Log the recovered value and debug.Stack() when recovering in a server; the value alone rarely locates the bug.
  • Only add MustX alongside an existing X, and only when the input is a compile-time constant.
  • Reproduce concurrency crashes with GOTRACEBACK=all before guessing.

Practice Exercises

  1. Move Eval's deferred closure body into a method func (p *parser) handle(err *error) and call it as defer p.handle(&err). Then change it to defer func() { p.handle(&err) }() and record which version still recovers, and why.
  2. Delete the panic(r) re-panic from Eval and add a deliberate bug to factor -- index p.toks[p.pos+5] -- then run the program. Report what the user sees and explain why that is worse than a crash.
  3. Remove the named results from safeDivide (make it (int, error) and return explicit values). Show what safeDivide(1, 0) now returns and explain the mechanism.
  4. Launch Eval inside a goroutine with a deliberate nil-map write in fail, once with a recover in the goroutine and once with the recover only in main. Record both outcomes and state the rule they demonstrate.