What are panic, recover, and defer in Go and how do they interact?
Understand how panic, recover, and defer interact in Go: stack unwinding, LIFO cleanup, and turning panics into errors, with clear code examples.
Expected Interview Answer
panic stops normal execution and begins unwinding the stack, defer schedules a function call to run as each frame unwinds, and recover — called inside a deferred function — stops the panic and lets the program resume normally.
When panic is called, the current function halts and its deferred calls run in LIFO order, then the same happens up the call stack until the program crashes. A deferred function can call recover to capture the panic value and regain control, returning execution to the caller of the recovering function rather than crashing. recover only works when called directly inside a deferred function during an active panic; anywhere else it returns nil. Idiomatic Go reserves panic/recover for truly exceptional situations and package boundaries, not for ordinary error flow.
- defer guarantees cleanup runs even during a panic
- recover lets libraries turn a panic into a returned error
- Deferred calls run in predictable LIFO order
- Keeps unrecoverable failures from silently corrupting state
- Allows graceful degradation at server request boundaries
AI Mentor Explanation
panic is like a sudden pitch invasion that stops the match immediately; defer is the standing instruction that the covers must be pulled and the scorebook closed no matter how play ends; recover is the ground authority stepping in during the chaos to restore order so the match can resume from the next over. Without that authority the whole fixture is abandoned — recover only works from inside that pre-arranged safety procedure.
Step-by-Step Explanation
Step 1
A panic starts
panic(v) halts the current function's normal execution and begins unwinding the stack.
Step 2
Deferred calls fire
As each frame unwinds, its deferred functions run in LIFO order, allowing cleanup.
Step 3
recover is attempted
A deferred function calls recover(); if a panic is active it returns the panic value and stops the unwinding.
Step 4
Control returns normally
Execution resumes in the caller of the function that recovered, as if it had returned normally.
Step 5
Or the program crashes
If no deferred recover intercepts the panic, unwinding reaches main and the program exits with a stack trace.
What Interviewer Expects
- Clear definitions of panic, recover, and defer
- That recover only works inside a deferred function during a panic
- Deferred calls run in LIFO order during unwinding
- Where control resumes after a successful recover
- That panic/recover is not a general exception mechanism
Common Mistakes
- Calling recover outside a deferred function and expecting it to work
- Using panic/recover as routine error handling
- Forgetting deferred calls execute in reverse order
- Assuming recover resumes at the panic point rather than the recovering function's caller
- Swallowing a recovered panic without logging or converting it to an error
Best Answer (HR Friendly)
“In Go, panic is like hitting an emergency stop, defer schedules cleanup that always runs even during that stop, and recover lets you catch the emergency and carry on instead of crashing. Together they let a program clean up safely and, when needed, turn a serious failure into a controlled result.”
Code Example
package main
import "fmt"
func safeDivide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return a / b, nil // panics if b == 0
}
func main() {
fmt.Println("start")
res, err := safeDivide(10, 0)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("result:", res)
}
fmt.Println("still running")
}Follow-up Questions
- Where does execution resume after a successful recover?
- Why does recover return nil when called outside a deferred function?
- How can a deferred function modify a named return value?
- When is using panic actually idiomatic in Go?
- What happens to deferred calls higher up the stack when a panic is recovered midway?
MCQ Practice
1. Where must recover be called to stop a panic?
recover only stops a panic when called directly inside a deferred function during an active panic.
2. In what order do deferred calls run when a function unwinds?
Deferred calls execute in last-in, first-out order as the frame unwinds.
3. After a deferred recover handles a panic, where does execution continue?
Control returns to the caller of the function that recovered, as if it had returned normally.
Flash Cards
What does panic do? — Stops normal execution and unwinds the stack, running deferred calls along the way.
What does recover do and where? — Called inside a deferred function during a panic, it captures the panic value and stops the unwinding.
In what order do deferred calls run? — LIFO — the most recently deferred call runs first.
Where does execution resume after recover? — In the caller of the function that recovered, as a normal return.
Continue Learning
Related Interview Questions
How does error handling work in Go and why does it not use exceptions?
medium
How does the defer statement work and in what order do deferred calls run?
medium
What are goroutines and how do they differ from OS threads?
medium
What are channels in Go and how do they enable communication between goroutines?
medium