Skip to content
Learn Netverks

Lesson

Step 32/36 89% through track

defer-panic-recover

Defer, panic, and recover

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
advanced

This lesson

This lesson teaches Defer, panic, and recover: the syntax, patterns, and safety habits you need before advancing in Go.

Teams still ship Defer, panic, and recover in Go codebases—skipping it leaves gaps in debugging and code reviews.

You will apply Defer, panic, and recover in contexts like: Kubernetes ecosystem tools, cloud APIs, and CLI utilities.

Write Go in main.go with package main and func main(), click Run on server—the dev runner runs go run main.go; use fmt.Println for output (requires Go toolchain; LEARNING_RUNNER_ENABLED=true).

When pointers, structs, and basic control flow from intermediate lessons are familiar.

defer schedules function calls at surrounding function return—LIFO order. Use for Close(), mutex unlocks, and tracing spans. panic unwinds the stack; recover catches panics inside deferred functions only.

defer patterns

f, err := os.Open("file")
if err != nil { return err }
defer f.Close()

Deferred calls evaluate arguments immediately but run at return—watch loop defer pitfalls (defer in loops stacks many calls).

panic/recover

Reserve for truly unexpected bugs—not control flow. HTTP servers sometimes recover per-request to return 500 instead of crashing the process.

Important interview questions and answers

  1. Q: defer order?
    A: Last deferred runs first on return.
  2. Q: recover outside defer?
    A: Ineffective—recover only works inside deferred functions during panic unwind.

Self-check

  1. When do deferred functions run?
  2. Should errors use panic?

Pitfall: defer inside loops stacks N defers—use a function literal or explicit cleanup in loops.

Interview prep

defer order?

LIFO—last deferred runs first on function return.

recover scope?

Only effective inside deferred functions during panic unwind.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • defer LIFO?
  • recover only defer?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump