Python Defer, Panic & Recover: Resource Cleanup
The defer keyword guarantees execution before function return (LIFO order). Panic terminates normal execution during critical invariant failures, while recover restores normal execution inside deferred functions.
"defer is like writing your checklist as you enter a rental car ("lock car upon return"). Even if you leave in a rush, the checklist executes as you step away."
Deep Dive: How It Works
LIFO Order: Deferred calls execute in Last-In, First-Out order right before the function returns.
Guaranteed Cleanup: defer guarantees execution even if panics or early returns occur.
Panic & Recover: panic halts goroutine execution; recover() inside a deferred function catches the panic.
Syntax Blueprint
defer f.Close()
defer func() {
if r := recover(); r != nil { fmt.Println(r) }
}()Schedule cleanup with defer; catch panics safely with recover inside deferred closures.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Putting defer inside a tight loop processing 10,000 files.Why it happens: Defers run at function exit, not loop iteration exit, leading to file descriptor exhaustion.
How to fix: Wrap loop body in a helper function so defers execute per iteration.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Protect a Division Function with Recover
Write a function safeDiv(a, b int) that has a deferred recover handler.
If a panic occurs, the handler should print "Recovered: division error".
Inside safeDiv, perform result := a / b and print "Result: %d".
In main(), call safeDiv(10, 0).
Finished reading and practicing?
Mark this lesson as completed to update your course progress.