← All notes

Go defer, panic and recover

Answer: In Go, defer schedules a function call to run when the surrounding function returns, which makes cleanup like closing files easy. panic stops normal execution and unwinds the stack, running deferred calls; recover, called inside a deferred function, stops a panic and lets the program continue.

Three rules of defer

  1. A deferred call's arguments are evaluated when the defer statement runs, not when the call happens.
  2. Deferred calls run in last-in, first-out order after the function returns.
  3. Deferred functions can read and set the function's named return values.
f, err := os.Open(name)
if err != nil { return err }
defer f.Close()

panic and recover

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

recover only has an effect inside a deferred function during a panic; otherwise it returns nil.

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: The Go Authors (go.dev), Defer, Panic, and Recover - The Go Programming Language, CC BY 4.0 (go.dev text); The Go Authors (go.dev), Effective Go - The Go Programming Language, CC BY 4.0 (go.dev text).

Cite this

Permanent ID: iil:note:e7ddbcp1

iinventedlight. 2026. "Go defer, panic and recover." iinventedlight Library, iil:note:e7ddbcp1, version of 2026-11-04. https://iinventedlight.com/library/notes/go-defer-panic-recover/. License: CC-BY-4.0.

@misc{iil_note_e7ddbcp1,
  author = {{iinventedlight}},
  title = {{Go defer, panic and recover}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-04},
  url = {https://iinventedlight.com/library/notes/go-defer-panic-recover/},
  note = {Permanent ID iil:note:e7ddbcp1. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/go-defer-panic-recover.md.