Defer, Panic, Recover
Go gives you three tools for cleanup and rare failures.
defer means: do this cleanup when you leave the room.
panic stops normal flow. recover can catch a panic inside a deferred function.
Everyday problems still use error values. panic is for unexpected situations.
defer basics
defer runs a call just before the surrounding function returns.
It is like putting away toys when you leave the room.
Great for closing files and unlocking locks.
Many defers stack
Deferred calls stack like plates.
The last one deferred runs first.
First in, last out.
panic
panic stops normal flow in the current goroutine after running deferred functions.
Return an error unless the program truly cannot continue.
Panic is the fire alarm, not the sticky note.
recover
recover only works inside a deferred function.
It stops the panic and gives you the panic value.
Then you can log it or turn it into an error.
When to use each tool
Use defer for cleanup you must not forget.
Use error values for normal problems.
Use panic and recover for rare, unexpected crashes you must contain.
You finished the Go course path. Practice with errors, goroutines, and defer.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.