Go defer, panic, and recover: Control Flow, Resource Cleanup, and Pitfalls
Deferred calls run LIFO with arguments captured at the defer, recover only works in the panicking frame's deferred function, and defer inside a loop leaks until the function returns.

defer schedules a call to run when the surrounding function returns; panic unwinds the stack running deferred calls; recover stops that unwind. The three exist to make cleanup unconditional and one class of failure survivable, and both purposes are easy to defeat: a defer whose arguments are evaluated too early, a recover in the wrong frame, or a panic converted into a nil error all leave the code worse than before.
Quick Summary
- Deferred calls run in LIFO order when the function returns, panics, or calls
runtime.Goexit. - Deferred arguments are evaluated when the
deferstatement executes, not when the call runs.defer f(x)capturesximmediately;defer func() { f(x) }()reads it later. - A deferred function can modify named return values, which is how
deferturns a panic into an error. recoveronly works when called directly by a deferred function in the frame that panicked. Called from another function, or outside adefer, it returnsniland does nothing.- A recovered panic stops unwinding; the function returns normally, so the caller gets whatever the return values are at that point.
panicshould be reserved for unrecoverable programming errors and for invariants that must never be violated. Ordinary failures areerrorvalues.deferin a loop defers to the end of the function, not the end of the iteration; loop-scoped cleanup belongs in an inner function.
Basic syntax and type signatures
func f() (err error) {
start := time.Now()
defer func() {
log.Printf("f took %s", time.Since(start)) // reads start at run time
}()
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("f panicked: %v", r)
}
}()
return nil
}
// Order: LIFO. The second defer runs first.
func order() {
for i := 0; i < 3; i++ {
defer fmt.Println(i) // prints 2, 1, 0
}
}
// Arguments captured at defer time.
func captured(x int) {
defer fmt.Println(x) // prints the value x had here
x++
fmt.Println(x) // prints x+1 now
}
func builtins() {
defer func() {
// recover must be called by the deferred function itself
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
panic("boom")
}The recover deferred function must be registered before the panic for it to run at all, and it must be the function that calls recover directly. defer recover() compiles and does nothing, which is the mistake that shows up as a program still crashing despite an apparent guard.
Comparison of the mechanisms
| Mechanism | Trigger | Runs on exit | Can change return | Typical use |
|---|---|---|---|---|
defer f() | function return, panic, Goexit | yes, LIFO | via named result | close, unlock, cancel |
panic(v) | explicit or runtime fault | starts unwinding | via recover | invariant violation |
recover() | only inside a deferred call | stops unwinding | yes | boundary guards |
errors.Join | — | — | returns an error | multiple failures |
explicit close | — | no, if a branch returns early | no | cleanup where defer is too coarse |
defer has a small cost per call — a few nanoseconds with open-coded defers since Go 1.14 — but the cost is not zero in the hottest loops, which is why the compiler's open-coded path only covers the common case of a defer without a loop or a recover in the same function.
Practical edge cases and deep dives
1. Named returns and the deferred error conversion
func readConfig(path string) (cfg Config, err error) {
f, err := os.Open(path)
if err != nil {
return Config{}, err
}
defer func() {
if cerr := f.Close(); cerr != nil && err == nil {
err = cerr // only set if nothing else failed
}
}()
if err = json.NewDecoder(f).Decode(&cfg); err != nil {
return Config{}, fmt.Errorf("decode %s: %w", path, err)
}
return cfg, nil
}
// The bare `return cfg, nil` above assigns to the named results first,
// so the deferred function sees and can rewrite `err`.A deferred closure that assigns to a named result affects what the caller receives. With unnamed results it cannot, because the values are already being copied out. The err == nil guard matters: overwriting a real error with a close error hides the cause, which is the reverse mistake of ignoring Close's error entirely.
2. Recovering at the right boundary, and re-panicking what is not yours
func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
if rec == http.ErrAbortHandler {
panic(rec) // let the server handle this one
}
s.logger.Error("panic", "err", rec, "stack", string(debug.Stack()))
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
s.route(w, r)
}A recover belongs at a goroutine boundary — an HTTP handler, a worker loop, a scheduled job — not in library functions. Each goroutine that panics without a recover takes the whole process down, so every go func() started by the program is a candidate. Re-panicking specific sentinel values (http.ErrAbortHandler is the documented one) preserves the framework's own behavior, and logging debug.Stack() at the moment of recovery is what makes the incident diagnosable later.
3. defer in a loop: the file-descriptor leak
// Wrong: every file stays open until the function returns.
func processAll(paths []string) error {
for _, p := range paths {
f, err := os.Open(p)
if err != nil {
return err
}
defer f.Close() // deferred to the end of processAll
if err := process(f); err != nil {
return err
}
}
return nil
}
// Right: an inner function gives each iteration its own deferred scope.
func processAllFixed(paths []string) error {
for _, p := range paths {
if err := processOne(p); err != nil {
return err
}
}
return nil
}
func processOne(p string) error {
f, err := os.Open(p)
if err != nil {
return err
}
defer f.Close()
return process(f)
}The wrong version opens every file before closing any, which exhausts the process's descriptor limit on a few thousand paths and produces too many open files under load rather than in a test. The inner-function form is the idiomatic fix; Go 1.22's loop variable change does not affect this, because the problem is the defer's scope, not the variable's.
4. panic with typed values and the error it produces
type ValidationPanic struct {
Field string
Why string
}
func mustValidate(v Validator) {
if err := v.Validate(); err != nil {
panic(ValidationPanic{Field: "input", Why: err.Error()})
}
}
func safeValidate(v Validator) (err error) {
defer func() {
if rec := recover(); rec != nil {
switch p := rec.(type) {
case ValidationPanic:
err = fmt.Errorf("%s: %s", p.Field, p.Why)
case error:
err = fmt.Errorf("internal: %w", p)
default:
panic(rec) // unknown panic: do not swallow it
}
}
}()
mustValidate(v)
return nil
}Panicking with an error value rather than a string keeps errors.Is and errors.As usable on the far side of the recover. The default: panic(rec) branch is the important line: converting an arbitrary panic into an error hides bugs, and the only panics that should become errors are the ones the code itself raises deliberately.
5. defer with methods, receivers, and nil pointers
type Conn struct{ closed bool }
func (c *Conn) Close() error {
if c == nil {
return nil
}
c.closed = true
return nil
}
func use(c *Conn) (err error) {
defer c.Close() // receiver evaluated now; a nil *Conn is fine if Close handles it
// defer c.Close() with a nil c and a method that dereferences: panic at return
return work()
}
func useNilSafe(c *Conn) error {
if c != nil {
defer c.Close()
}
return work()
}The receiver of a deferred method call is evaluated at defer time, so defer c.Close() on a pointer that is later reassigned closes the original value. A nil receiver in a deferred call panics when the deferred call runs — at the return, far from the line that caused it — which is why the nil check belongs at the defer site rather than inside the callee when the type does not handle nil.
Common mistakes and compiler errors
| Symptom | Cause | Fix |
|---|---|---|
| The intended error is replaced by a close error | deferred assignment overwrote a non-nil error | guard with if err == nil |
Program still crashes despite recover | recover called outside a deferred function, or in a different frame | call it directly inside defer func() { ... }() |
defer prints the wrong value | arguments evaluated at defer time | close over the variable instead of passing it |
too many open files | defer inside a loop holds resources until return | move cleanup into an inner function |
| Cleanup does not run | os.Exit skips deferred calls | run cleanup before exiting, or return an error to main |
Deferred Unlock runs after a panic in the same section | defer mu.Unlock() was not registered | register it immediately after Lock |
runtime error: invalid memory address at function return | deferred call on a nil receiver | guard for nil before deferring |
| Lost stack trace | panic converted to an error without logging the stack | log debug.Stack() at the recovery point |
The design rule that keeps these out of the code: defer is for cleanup that must happen no matter how the function exits, panic is for states the program cannot continue from, and recover belongs only at goroutine boundaries where a failure is contained and reported. When a recover appears in the middle of a library, the panic it catches is usually a bug that should be fixed, and the error it produces erases the stack that would have shown where.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.