Ppens When A Panic Occurs
Fast recall
Quick revision
Core answer
Practical understanding of Panic Vs Error.
Repeating a definition without saying when to use it.
Give one trade-off and say how you would test it.
Interview-ready guide
Interview answer
When panic is called, the current function stops at that line. Its deferred calls run — this is the key behavior — then the caller's deferred calls, and so on up the goroutine's stack, in reverse order of how they were set up. That's LIFO: what was deferred last runs first.
If any deferred function along the way calls recover, the unwinding stops there and that function returns normally. If none does, the whole program prints the panic value with a goroutine dump and exits with a non-zero status. One goroutine's unrecovered panic kills every goroutine — the process goes down together.
func safeCall() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panicked: %v", r) // this defer runs during unwind
}
}()
doWork() // panics → deferred closure runs LIFO → converted to err
return nil
}Ppens When A Panic Occurs
Direct Answer
The goroutine unwinds: deferred functions run in LIFO order, then if nothing recovers, the program prints the panic value and stack trace and exits.
Deep Dive & Architecture
The unwinding order is what makes defer/recover work at all. Consider the pattern:
When doWork panics, the deferred closure runs first — because it was deferred in this function — and recover grabs the panic value before the unwind escapes. If the defer were placed AFTER doWork, the panic would pass the function before the closure was registered: recover has to be set up before the dangerous call, which is why defer sits at the top of the function.
The stack trace the runtime prints is the unwind path — the panic site plus every frame it passed through. That's why panics are diagnostic gold when they're genuine bugs: the trace tells you exactly which impossible state occurred and where.
Common Mistakes & Pitfalls
Repeating a definition without saying when to use it.
Check your understanding
Answer these without looking back at the article.
- What is Panic Vs Error, and when would you use it?
- What is a common mistake when using Panic Vs Error?
- How would you compare Panic Vs Error with an alternative?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.