Defer, Panic, Recover — Go

defer f() runs f when the function holding it ends, through a return or a panic. Several defers run LIFO: the last one pushed runs first, so defer A, B, C…

Bimo opens a bill for table 4. As soon as the bill is open, he pins a note saying "close the bill" on the board. Whatever happens next, the order goes fine or the stove suddenly dies, the note on the board gets done before he leaves the table. The note pinned last sits on top, so it gets done first.

In Go, that note is defer: it schedules a function call so it only runs when the function holding it ends. The stove that suddenly dies is panic, which stops the program in an emergency. recover catches that panic from inside a deferred function.

defer: runs when the function ends

package main

import "fmt"

var menu = []string{"tendon meatballs", "chicken noodles", "iced tea"}

func serve(table, item int) {
	fmt.Println("table", table, "opens the bill")
	defer fmt.Println("table", table, "closes the bill")
	fmt.Println("table", table, "orders", menu[item])
}

func main() {
	serve(4, 1)
	fmt.Println("the stall stays open")
}
$ go run stall.go
table 4 opens the bill
table 4 orders chicken noodles
table 4 closes the bill
the stall stays open

LIFO order, and arguments worked out right away

With several defers, the one pushed last runs first. This order is called LIFO (last in, first out), like a stack of plates:

func main() {
	defer fmt.Println("A")
	defer fmt.Println("B")
	defer fmt.Println("C")
	fmt.Println("start")
}

The output is start, then C, B, A, each on its own line.

A defer's arguments are worked out when the defer line runs, not when the function ends:

portions := 1
defer fmt.Println("defer sees portions:", portions)
portions = 3
fmt.Println("portions now:", portions)

This prints portions now: 3 then defer sees portions: 1. The value 1 was stored when the defer line went past. If what is deferred is a closure, defer func() { fmt.Println(portions) }(), the closure reads the variable when it runs, so it sees 3.

The cleanup pattern: open, then defer the close right away

The open and the close are written side by side, so the close can't be forgotten: f, err := os.Open("menu.txt") then defer f.Close(), or mu.Lock() then defer mu.Unlock(). This lesson's exercise uses the same pattern with two resources. openResource prints open: <name>, closeResource prints close: <name>:

a := openResource("file-A")
defer closeResource(a)

b := openResource("file-B")
defer closeResource(b)

fmt.Println("working...")
open: file-A
open: file-B
working...
close: file-B
close: file-A

file-B was opened last, so it is closed first. That is the right order for resources that depend on each other.

Panic: an emergency stop

Now main calls serve(4, 5). menu[5] from a slice of 3 can't be done, so Go panics. Before you look at the output, guess: does the deferred line table 4 closes the bill still get printed?

$ go run stall.go
table 4 opens the bill
table 4 closes the bill
panic: runtime error: index out of range [5] with length 3

goroutine 1 [running]:
main.serve(0x4, 0x5)
	/home/bimo/stall/stall.go:10 +0x219
main.main()
	/home/bimo/stall/stall.go:14 +0x1d
exit status 2

Recover: catching a panic inside a defer

func serve(table, item int) {
	fmt.Println("table", table, "opens the bill")
	defer fmt.Println("table", table, "closes the bill")
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("table", table, "failed:", r)
		}
	}()
	fmt.Println("table", table, "orders", menu[item])
}
$ go run stall.go
table 4 opens the bill
table 4 failed: runtime error: index out of range [5] with length 3
table 4 closes the bill
the stall stays open

When to panic, when to return an error

What happens Use
A customer's wrong input, out of stock, file not found, network timeout return an error
A programmer's bug: a value the logic says is impossible panic
A failure at startup that leaves the program unable to run at all panic

Almost every failure in Go is an ordinary error value. recover is not a try/catch replacement: use it at a boundary, for example so one failed order doesn't bring down the whole till.

⚠️ Defer and recover that don't run the way you expect

TL;DR: defer f() runs f when the function holding it ends, through a return or a panic. Several defers run LIFO: the last one pushed runs first, so defer A, B, C then start prints start C B A. A defer's arguments are worked out when the defer line goes past. The cleanup pattern: open, then defer the close right away. panic stops the function, runs every defer, prints panic: ... with a stack trace, then exits with exit status 2. recover() inside a deferred function catches the panic and lets the program go on; anywhere else it returns nil. Use error for ordinary failures, panic for bugs and startup failures.

⚡ It runs when the function ends

Write:

fmt.Println("table", table, "opens the bill")
defer fmt.Println("table", table, "closes the bill")
fmt.Println("table", table, "orders", menu[item])

Meaning: The defer line prints nothing yet. The call is stored, then run just before the function returns, so closes the bill prints last.

⚡ The last one pushed runs first

Guess first: defer prints A, then B, then C, and only then fmt.Println("start"). What is the order of the output?

start, then C, B, A. Defers run LIFO (last in, first out), like a stack of plates.

Meaning: The cleanup pattern: open, then defer the close right away. What was opened last is closed first.

⚡ Panic and recover

Write:

defer func() {
	if r := recover(); r != nil {
		fmt.Println("table", table, "failed:", r)
	}
}()

Meaning: A panic stops the function, but the defers already pushed still run. recover() inside a deferred function catches the panic, so the program goes on. Outside a defer, recover() returns nil.

What you will learn