Defer, Panic & Recover in Go

From the Go cheat sheet ยท Error Handling ยท verified Jul 2026

Defer, Panic & Recover

Deferred execution, panics, and recovery

go
// Defer: runs when function returns (LIFO)
f, _ := os.Open("file.txt")
defer f.Close() // Guaranteed cleanup

// Panic: unrecoverable error
panic("something went wrong")

// Recover: catch panics
defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered:", r)
    }
}()
๐Ÿ“Œ defer runs in LIFO order when the function returns
๐ŸŽฏ Always defer Close(), Unlock(), Done() right after acquiring
โš ๏ธ Only recover from panics at package boundaries โ€” don't use as try/catch
๐Ÿ’ก Deferred functions can modify named return values

More Go tasks

Back to the full Go cheat sheet