In Go, defer schedules a function call to run when the surrounding function returns, panic stops normal execution and starts unwinding the stack for unrecoverable problems, and recover regains control inside a deferred function so a panic can be handled. defer is for cleanup, panic is for programmer errors and impossible states, and recover is a narrow safety net, not a general error-handling tool.
Ordinary failures such as a missing file or invalid input should be returned as error values. Reserve panic for situations where continuing is not meaningful.
A defer statement evaluates the function value and its arguments immediately, but runs the call later, when the enclosing function exits by returning normally, by panic, or by runtime.Goexit. Multiple deferred calls run in last-in, first-out order.
The classic use is releasing resources next to where they are acquired:
Details worth knowing:
defer statement, not when the call runs.Close are often merged into the result.defer inside a loop delays every call until the function ends. In long loops, wrap the body in a helper function so resources are released per iteration.defer has very low overhead in normal code, so do not avoid it for performance reasons.panic(v) stops the current function, runs its deferred calls, then continues unwinding up the call stack running deferred calls at each level. If nothing recovers, the program prints the panic value and a stack trace and exits with status 2.
Panics also happen implicitly: nil pointer dereference, index out of range, writing to a nil map, closing a closed channel, and failed type assertions without the ok form.
Use panic for bugs and invariant violations, for example in initialization where the program cannot work without a valid value. Do not use it for expected failures or as a replacement for exceptions across package boundaries.
recover() returns the value passed to panic and stops the unwinding, but only when called directly by a deferred function while the goroutine is panicking. Called anywhere else, it returns nil.
Here the named result err lets the deferred function turn a panic into an ordinary error. Two rules matter: recover only works in the same goroutine that panicked, and a panic in another goroutine you started will crash the whole program unless that goroutine has its own deferred recover.
| Feature | defer | panic | recover |
|---|---|---|---|
| Kind | Statement | Built-in function | Built-in function |
| Purpose | Run cleanup at function exit | Abort normal flow on a fatal condition | Intercept a panic and resume |
| When it runs | When the surrounding function returns | Immediately | Only inside a deferred function |
| Typical use | Close files, unlock mutexes, end spans | Impossible states, programmer bugs | Servers isolating a failed request, converting to errors |
| Returns | Nothing | Nothing | The panic value, or nil |
mu.Lock() followed by defer mu.Unlock().runtime/debug.Stack()) and returns a 500 or restarts the worker. The net/http server already recovers panics per request and logs them.error, wrap with fmt.Errorf("...: %w", err), and check with errors.Is and errors.As.panic(r) again.No. os.Exit ends the process immediately without running deferred calls. log.Fatal calls os.Exit too.
Almost all, but not fatal runtime errors such as concurrent map writes or running out of memory, which terminate the program.
Yes, in normal code. Go convention is explicit error returns, with panic for truly exceptional bugs.
Last in, first out, so the most recently deferred call runs first.
defer guarantees cleanup, panic signals an unrecoverable condition, and recover lets a deferred function stop a panic at a well-chosen boundary. Return errors for expected failures, use defer freely for resource release, and keep panic and recover rare and deliberate.