go · level 2 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Out of biscuits! What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
defer func() {
v := recover()
fmt.Println("Caught:", v)
}()
fmt.Println("Start")
panic("out of biscuits")
fmt.Println("End")
}
your turn
Your turn. Keep the cake server alive.
Make the cake handler panic with any message you like. Then fill in the built-in command that catches the panic inside the deferred function.
output
press run to see what happens
fix it
The safety net is in the wrong place. Fix it!
output
press run to see what happens
- The program still crashes. Here, does
recoverrun before the job starts, or after the panic? recoveronly works inside a deferred function, which runs while the panic passes through.- Wrap the if block in defer func() { ... }() at the top of safely, then run.
nailed it
your server survives the worst. :D
panicis for things that should never happen.recoveronly works inside a deferred function.- A wrapper that recovers turns a panic into a 500 reply.
new words in your collection
- recover
- wrapper
This lesson isn’t saved. A free account remembers every lesson you finish.