×

go · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

catches a panic before it crashes everything.

panic("the oven is on fire") causes a panic on purpose. Save it for things that should never happen, such as a mistake in your own setup. For bad input, return an error instead. A panic stops the function, but its deferred calls still run.

Inside a deferred function, recover() catches the panic and gives back its value, or nil when nothing went wrong. Write it as defer func() { ... }(): a function literal with () at the end, so it gets called.

A is a function that runs other code with extra care around it. safely(job func()) takes a function and runs it with recover standing by. Web servers wrap every handler like this and answer 500 when one panics, so the server stays up.

package main
import "fmt"
func safely(job func()) {
	defer func() {
		if v := recover(); v != nil {
			fmt.Println("Recovered:", v)
		}
	}()
	job()
}
func main() {
	safely(func() {
		fmt.Println("Baking a cake")
	})
	safely(func() {
		panic("the oven is on fire")
	})
	fmt.Println("The bakery stays open")
}

job func() is a parameter whose type is a function with no parameters and no results.