Stage 1 · Code
Methods, Interfaces & Errors
panic and recover
Understand when panic is the right tool, how defer always runs, and why recover is narrow by design.
defer
defer schedules a function call to run when the surrounding function returns — regardless of whether it returns normally or panics. Deferred calls run in LIFO order (last deferred, first run).
When you write defer fmt.Println(x), the current value of x is captured right then — not when the deferred call eventually runs. Only the execution of the call itself is deferred. This matters when you want to defer with the value x has at the time of the defer, not the value it will have at function exit.
panic
panic stops normal execution, unwinds the call stack running deferred functions, and terminates the program with a message. Use panic only for programming errors that should never happen in correct code.
recover
recover() can stop a panic in progress and return the panic value. It only works inside a deferred function. After recovery, execution continues normally — but only in the goroutine where the deferred function ran.
panic vs Error Returns
The Go community has a clear convention: return errors for expected failure paths, use panic only for programmer bugs and truly unrecoverable states.
| Situation | Use |
|---|---|
| User input is invalid | return err — expected, recoverable |
| Network request failed | return err — expected, recoverable |
| A nil pointer that should never be nil | panic — programming error |
| Index out of bounds you should have prevented | panic — programming error |
| Required config is absent at startup | log.Fatal or panic — unrecoverable startup failure |
| Third-party library panics unexpectedly | recover in a middleware wrapper |
Some parsers and complex recursive algorithms use panic internally as a long-jump and recover at the top to return a clean error. This is acceptable if the panic never escapes the package boundary. The json package in the standard library uses this technique.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.