Defer, Panic and Recover

defer is a to-do list that runs when the function ends, newest item first.

The idea

You are leaving a house. You think of chores as you go: “turn off the oven”, then “lock the window”, then “lock the door”. Before you can leave you must undo them in reverse: door first (it was added last), then window, then oven. That is defer: a last-in, first-out stack of calls that run when the surrounding function returns, even if it returns because of a panic.

A panic is an emergency: normal execution stops and Go unwinds the stack, running deferred calls. If a deferred function calls recover(), the emergency is cancelled and the function returns normally. If nobody recovers, the program crashes.

Watch it work

Try it

Common mistakes