Coding/Learn/go/go defer panic recover
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnDefer, Panic & Recover: Resource Cleanup
12 / 20 0%
Lesson 12 of 20
13 mins read

Defer, Panic & Recover: Resource Cleanup

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
LIFO Execution: Defers execute in reverse order of declaration.
Point star
Immediate Argument Evaluation: Arguments to deferred functions are evaluated at defer statement time, not at function exit.
Point star
Panic Fences: recover() stops unwinding and restores normal flow only when called inside defer.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Always place defer file.Close() or defer mu.Unlock() on the line immediately following successful resource acquisition.

Live Interactive Example

Hit Run Code to see it live
LIFO Defer Execution and Panic Recovery
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Output Console
Click "Run Code" to view the rendered output.
How it works: Deferred calls fired in reverse order (3, 2, 1). Defer 2 caught the panic and prevented process crash.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Protect a Division Function with Recover

  • PointWrite a function safeDiv(a, b int) that has a deferred recover handler.
  • PointIf a panic occurs, the handler should print "Recovered: division error".
  • PointInside safeDiv, perform result := a / b and print "Result: %d".
  • PointIn main(), call safeDiv(10, 0).
1
2
3
4
5
6
7
8
9
10
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates