TExcelTAD
Home › Go › Go Defer, Panic & Recover

Go Defer, Panic & Recover

Three keywords control what happens when a function finishes — normally or abnormally:

Keyword What it does
defer schedules a function call to run when the surrounding function returns
panic stops normal execution and starts unwinding the stack
recover inside a deferred function, stops a panic and returns its value

defer

A deferred call runs just before the function returns — whether it returns normally, early, or because of a panic. It is Go's tool for clean-up: closing files, unlocking mutexes, printing "done" messages.

go · try it yourself
package main

import "fmt"

func process(name string) {
	fmt.Println("open", name)
	defer fmt.Println("close", name) // runs at the end, guaranteed

	if name == "" {
		fmt.Println("empty name, stopping early")
		return
	}
	fmt.Println("working on", name)
}

func main() {
	process("report.csv")
	process("")
}
open report.csv
working on report.csv
close report.csv
open 
empty name, stopping early
close 

Putting defer f.Close() right after a successful os.Open keeps the opening and the clean-up next to each other, so you cannot forget it.

Deferred calls run last-in, first-out

Multiple defers form a stack: the last one deferred runs first.

go · try it yourself
package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		defer fmt.Println("deferred", i)
	}
	fmt.Println("main body done")
}
main body done
deferred 3
deferred 2
deferred 1

Arguments are evaluated immediately

The arguments of a deferred call are evaluated when the defer statement runs, not when the call happens. A deferred closure, however, sees the variables' final values.

go · try it yourself
package main

import "fmt"

func main() {
	x := 1
	defer fmt.Println("argument captured at defer time:", x)
	defer func() {
		fmt.Println("closure sees the final value:", x)
	}()
	x = 99
}
closure sees the final value: 99
argument captured at defer time: 1

panic

A panic signals a bug or a situation the program cannot handle: an index out of range, a nil map write, or an explicit panic("..."). The current function stops, deferred calls run, and the panic travels up the call stack. If nothing recovers it, the program crashes and prints a stack trace.

Use panic for programmer errors and impossible states — not for expected failures like "file not found". Those should be returned as error values.

recover

recover() only works inside a deferred function. If the goroutine is panicking, it stops the panic and returns the value passed to panic; otherwise it returns nil. This lets you turn a panic into a normal error at a boundary — for example, so one bad request doesn't crash a whole web server.

go · try it yourself
package main

import (
	"fmt"
)

func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

func mustPositive(n int) int {
	if n < 0 {
		panic(fmt.Sprintf("negative value %d", n))
	}
	return n
}

func try(n int) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
		}
	}()
	fmt.Println("value:", mustPositive(n))
	return nil
}

func main() {
	fmt.Println(safeDivide(10, 2))
	fmt.Println(safeDivide(1, 0))

	fmt.Println(try(5))
	fmt.Println(try(-3))
	fmt.Println("program keeps running")
}
5 <nil>
0 recovered: runtime error: integer divide by zero
value: 5
<nil>
negative value -3
program keeps running

Notice how a deferred function can change named result values (err) — that is how the recovered panic becomes the function's returned error.

A realistic pattern: measuring and logging

defer is great for "before and after" work. Here it reports how many steps a function took, without repeating code at every return:

go · try it yourself
package main

import "fmt"

func search(items []string, target string) (found bool) {
	steps := 0
	defer func() {
		fmt.Printf("search %q: found=%v after %d steps\n", target, found, steps)
	}()
	for _, it := range items {
		steps++
		if it == target {
			return true
		}
	}
	return false
}

func main() {
	list := []string{"ant", "bee", "cat", "dog"}
	search(list, "cat")
	search(list, "eel")
}
search "cat": found=true after 3 steps
search "eel": found=false after 4 steps

Note: A panic in one goroutine can only be recovered by a deferred function in that same goroutine. An unrecovered panic in any goroutine crashes the whole program.

Test yourself

In what order do three deferred calls run?

  1. In the order they were deferred
  2. In reverse order (last in, first out)
  3. Randomly
  4. Only the last one runs

Where does recover() have an effect?

  1. Anywhere in the program
  2. Only in main
  3. Only directly inside a deferred function
  4. Only after panic returns

Should you use panic when a user enters an invalid email address?

  1. Yes, always
  2. No — return an error for expected failures
  3. Only in web servers
  4. Only with recover