panic, recover and the boundary
A panic stops the current function, runs its defers, and repeats in the caller until something recovers it or the program dies. It is for bugs and for states the programmer believed impossible, not for ordinary failures: an error is a value a caller handles, and a panic is a stack that unwinds. The defer lesson explained what runs during the unwind; this one explains who can stop it.
Recover belongs to a deferred call
recover() returns the panic value and stops the unwind, but only when it is called directly by a function that is running as a defer. The deferred closure both recovers and writes the named error result, so the caller sees an ordinary error where a panic had started. The division by zero is a runtime error, a panic the runtime raises.
package main
import "fmt"
func safeDiv(a, b int) (q int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return a / b, nil
}
func main() {
q, err := safeDiv(1, 0)
fmt.Println(q, err)
q, err = safeDiv(9, 3)
fmt.Println(q, err)
}
go run recover.go
0 recovered: runtime error: integer divide by zero
3 <nil>
The failed division returned 0 and a recovered error, and the good one returned 3 and nil: the caller cannot tell that a panic happened inside. That is the point of a boundary, and also the danger: a recover that swallows the value without recording it hides a bug that the stack would have shown.
recover outside a defer is nil
Called from an ordinary function, recover returns nil, because there is no panic in progress to stop. This is why a helper that calls recover directly looks like it works and never does: the recover must be written in the deferred function itself, or in a function that the defer calls and that recovers there.
package main
import "fmt"
func check() any {
return recover()
}
func contains(f func()) (panicked bool) {
defer func() {
if recover() != nil {
panicked = true
}
}()
f()
return false
}
func main() {
fmt.Println("recover outside a defer:", check())
fmt.Println("panic seen by the helper:", contains(func() { panic("boom") }))
fmt.Println("no panic:", contains(func() { fmt.Println("ran") }))
}
go run outside.go
recover outside a defer: <nil>
panic seen by the helper: true
ran
no panic: false
The first print is nil, the second is true, and the third printed ran and returned false. A helper that wraps a call in defer recover() is the safe way to test whether something panics, and it is what the standard library does in a few places where a panic is part of the contract.
Turning a panic into an error
A library that calls into code it does not trust, such as a plugin or a decoder of user input, puts a recover at its public boundary and returns an error. The panic value is usually kept as text and the error is wrapped with a sentinel, so the caller can test it with errors.Is like any other failure, and a panic never escapes into a server loop that would die with it.
package main
import (
"errors"
"fmt"
)
var ErrInternal = errors.New("internal error")
func decode(s string) (n int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("decode %q: %w", s, ErrInternal)
}
}()
if s == "" {
panic("empty input")
}
return len(s), nil
}
func main() {
n, err := decode("abc")
fmt.Println(n, err)
n, err = decode("")
fmt.Println(n, err, errors.Is(err, ErrInternal))
}
go run boundary.go
3 <nil>
0 decode "": internal error true
The second decode returned an internal error that matched the sentinel, and the panic text appears in the message for the log. Note that the named result is what makes this possible: a deferred function cannot change a result that is not named, so the signature is part of the design.
An unrecovered panic ends the program
Without a recover, the panic reaches the top of the stack, the runtime prints the value and the stack of every goroutine, and the process exits with status 2. A panic in a goroutine that main started is not recoverable from main: the goroutine has its own stack, and its panic ends the whole program. That is why a worker goroutine needs its own recover at the top of its function.
package main
import "fmt"
func main() {
fmt.Println("before the panic")
panic("boom")
}
go build -trimpath -o boom unrecovered.go
GOTRACEBACK=none ./boom 2>&1
./boom >/dev/null 2>&1; echo status: $?
before the panic
panic: boom
status: 2
With GOTRACEBACK=none the runtime prints only the panic value; the default prints the goroutine and frame lines too. The status is 2 and nothing after the panic ran, which is what a supervisor process sees and what a test asserts with a subprocess.
Exercises
- Write a function that panics with an error value and a boundary that recovers it and returns it, so errors.Is still works in the caller.
- Call recover() directly in main and inside a deferred closure. Explain the two results with the rule about where recover must run.
- Start a goroutine that panics and see what main does. Add a deferred recover at the top of the goroutine and run it again.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Where must recover be called to stop a panic?
Answer
Directly in a function running as a defer
recover outside a deferred call returns nil and leaves the panic running.
-
What does this program print?
package main import "fmt" func safeDiv(a, b int) (q int, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("recovered: %v", r) } }() return a / b, nil } func main() { q, err := safeDiv(1, 0) fmt.Println(q, err) q, err = safeDiv(9, 3) fmt.Println(q, err) }Answer
0 recovered: runtime error: integer divide by zero / 3 <nil>
The deferred closure recovered, wrote the error and left q at its zero value; the good call returned 3.
-
What does recover return when there is no panic?
Answer
nil
No panic in progress means nothing to recover, so the result is nil.
-
What does the first line of this program print?
package main import "fmt" func check() any { return recover() } func contains(f func()) (panicked bool) { defer func() { if recover() != nil { panicked = true } }() f() return false } func main() { fmt.Println("recover outside a defer:", check()) fmt.Println("panic seen by the helper:", contains(func() { panic("boom") })) fmt.Println("no panic:", contains(func() { fmt.Println("ran") })) }Answer
recover outside a defer: <nil> / panic seen by the helper: true / ran / no panic: false
check calls recover without a defer in progress, so it returns nil.
-
What does an unrecovered panic do to the process?
Answer
Prints the value and stack and exits with status 2
The runtime ends the program; a test sees the non-zero status.
-
What does the second line of this program print?
package main import ( "errors" "fmt" ) var ErrInternal = errors.New("internal error") func decode(s string) (n int, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("decode %q: %w", s, ErrInternal) } }() if s == "" { panic("empty input") } return len(s), nil } func main() { n, err := decode("abc") fmt.Println(n, err) n, err = decode("") fmt.Println(n, err, errors.Is(err, ErrInternal)) }Answer
3 <nil> / 0 decode "": internal error true
The boundary turned the panic into a wrapped internal error, which matches the sentinel.
-
Why can a panic in another goroutine not be recovered from main?
Answer
The goroutine has its own stack, and its panic ends the whole program
Each goroutine unwinds on its own stack; the recover must be in that goroutine.
-
When is panic the right tool?
Answer
For a bug or an impossible state, not for a failure the caller can handle
Errors are values for expected failures; panic is for broken invariants.
-
What does this program print?
package main import "fmt" func main() { fmt.Println("before the panic") panic("boom") }Answer
panic: boom
Nothing after the panic runs, the value is printed, and the exit status is 2.
-
What does a boundary that recovers a panic usually return?
Answer
An error that wraps a sentinel and keeps the panic text
The caller gets a testable error and the log keeps the text.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev