Go panic and recover let a program deal with errors that are too serious for a normal return value. In this post, you will learn how defer schedules work, what a panic does and how recover stops a crash. Each idea comes with a short example that you can run yourself.
Still, you should handle most problems with error values. For a refresher, see error handling in Go for beginners. You also used defer to close files in Go file handling with examples. Now you will see how it really works.
Go Panic and Recover Start with defer
defer delays a function call until the surrounding function returns. So it is perfect for clean-up work, such as closing files or unlocking a mutex. In fact, Go panic and recover both depend on it.
func order() {
for i := 1; i <= 3; i++ {
defer fmt.Println("defer", i)
}
fmt.Println("function body")
}
// function body
// defer 3
// defer 2
// defer 1
Deferred calls run in reverse order, last in first out. Think of a stack of plates: you take the top plate first.
Arguments Are Evaluated Early
x := 1
defer fmt.Println("deferred x =", x)
x = 2
fmt.Println("current x =", x)
// current x = 2
// deferred x = 1
Go evaluates the arguments when it reaches the defer line, not when the call runs. As a result, the deferred call still sees the old value.
What Is a Go Panic?
A panic stops the normal flow of a function. Go then runs every deferred call on the way up, and finally the program crashes with a message. For example, reading past the end of a slice causes a panic.
nums := []int{1, 2, 3}
i := 5
fmt.Println(nums[i])
// panic: runtime error: index out of range [5] with length 3
You can also panic on purpose with panic("message"). However, keep that for truly impossible situations, such as broken setup code at startup.
Go Panic and Recover Together
recover catches a panic and lets the program continue. It only works inside a deferred function, because deferred calls are the only code that still runs during a panic. The diagram below shows the full journey.

The panic travels up through the deferred calls, and recover inside a deferred function turns it back into a normal return.
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
}
fmt.Println(safeDivide(10, 2)) // 5 <nil>
fmt.Println(safeDivide(1, 0)) // 0 recovered: runtime error: integer divide by zero
Here the deferred closure catches the divide by zero panic. Then it turns the panic into a normal error. This trick uses named results, so the deferred function can still set err.
recover Outside defer Does Nothing
fmt.Println(recover()) // <nil>
If no panic is happening, recover simply returns nil. Also, calling it outside a deferred function never stops a panic.
When to Use Go Panic and Recover
| Situation | Use |
|---|---|
| File not found, bad user input | Return an error |
| Network call fails | Return an error |
| A bug that should never happen | panic |
| Library must not crash its caller | recover at the boundary, return an error |
| Web server handler panics | The net/http server already recovers for you |
In short, errors are for expected problems, and panics are for bugs. Go panic and recover should stay rare in everyday code. In fact, the standard net/http server recovers panics in each handler. So one bad request does not stop the whole Go HTTP server.
Common Mistakes with Go Panic and Recover
| Problem you see | Why it happens | How to fix it |
|---|---|---|
| Program still crashes | recover was not called inside a deferred function. | Call it inside defer func() { ... }(). |
| Panic in a goroutine kills the program | Each goroutine needs its own recover. | Add a deferred recover inside that goroutine. |
| Deferred value looks old | Arguments were evaluated at the defer line. | Use a closure to read the latest value. |
| Code panics for normal problems | Panic was used instead of an error. | Return an error value. |
Defer order and recover rules are popular interview questions. So test yourself with my Go interview questions and answers.
Official Resources
These pages come straight from the Go team, so they stay accurate and up to date.
Quick Recap
deferruns a call when the function returns, in reverse order.- Deferred arguments are evaluated at the defer line.
- A panic unwinds the stack and runs every deferred call.
- Go panic and recover work together only inside a deferred function.
- Use errors for expected problems and panic only for bugs.
What’s Next?
Your programs can now survive surprises. Next, we will look inside interface values with type assertions and type switches.
Next lesson: Go Type Assertion and Type Switch Explained


