Panic And Recover Basics
Fast recall
Quick revision
Core answer
Whether you understand Panic And Recover Basics beyond memorized syntax.
Giving a definition without explaining a practical trade-off.
Connect the concept to a small production example and state its complexity or failure mode.
Interview-ready guide
Interview answer
The mechanics, executed:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r) // "recovered: boom"
}
}()
panic("boom")
// never reached
}
// prints: recovered: boom
// — then main returns NORMALLY; the program continuesPanic And Recover Basics
Direct Answer
panic stops normal execution and unwinds the stack (running defers LIFO). recover — ONLY inside a deferred function during a panic — stops the unwinding and returns the panic value. The pair is Go's crash-with-hatch mechanism, not error handling.
Deep Dive & Architecture
The sequence: panic("boom") starts unwinding main; main's deferred function runs (LIFO — the only one registered); inside it, recover() detects the active panic, stops the unwind, and hands you the panic value. The deferred function returns; main returns normally (to its caller, the runtime); execution continues.
The restrictions that make it what it is: recover is ONLY meaningful inside a deferred function DURING a panic — elsewhere it returns nil. And a goroutine's panic can only be recovered in THAT goroutine — each goroutine unwinds its own stack, which is why worker goroutines need their own deferred recover (the goroutines topic).
The legitimate uses, short because the panic topic covers the 'when': converting panics to errors at API boundaries (a library that panics internally wraps its entry points with recover → error), and genuinely unrecoverable invariants where crashing is correct (but then you don't recover).
What it's NOT: Go's try/catch. Errors are returned values — the (T, error) pattern; panic/recover is the crash mechanism with a hatch. Using recover as routine control flow fights the language's explicit error design — the errors topic's whole argument.
Common Mistakes & Pitfalls
Giving a definition without explaining a practical trade-off.
Check your understanding
Answer these without looking back at the article.
- When would you use Panic And Recover Basics in a real project?
- How would you compare Panic And Recover Basics with an alternative?
- What is a common mistake when using Panic And Recover Basics?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.