Recover in Go
Start with Recover in Go
recover lets an appropriately deferred function stop a panic during stack unwinding, often at a well-defined boundary.
What you’ll learn
- Explain the main purpose of recover in go.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Call recover() directly within a deferred function running in the same goroutine as the panic. If it successfully recovers, the panicking function does not resume after the panic site; it returns to its caller.
Recovery can be useful in a top-level worker boundary that turns unexpected panics into controlled failures and records diagnostic information. It should not be used to silently hide errors or replace routine error checking.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func run() {
defer func() {
if problem := recover(); problem != nil {
fmt.Println("Handled:", problem)
}
}()
panic("problem in task")
}
func main() {
run()
fmt.Println("Program continues")
}
Output
Handled: problem in task
Program continuesTrace what the program does
The deferred function receives the panic value and handles it. After run returns, main proceeds and prints Program continues.
Avoid common mistakes
- A recover call outside the appropriate deferred panic path does not stop the panic.
- recover does not let the program continue from the statement immediately after the panic.
Try it yourself
Add a print before the panic and another immediately after it. Predict which one never executes.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Recover in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.