defer is a to-do list that runs when the function ends, newest item first.
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.
cleanup still prints before the crash message.recover() only works when called directly inside a deferred function. Elsewhere it returns nil.defer line runs, not when it executes.error instead; keep panic for bugs and impossible states.