Distinguish panic, recover and ordinary errors
Distinguish panic, recover and ordinary errors
Return errors for expected failures. Panic interrupts normal execution and unwinds the current goroutine’s call stack, running deferred calls. Recover can stop that panic when called directly by a deferred function in the panicking goroutine. Recovery is a boundary tool, not a substitute for checking ordinary errors.
package main
import ( "fmt")
func fail() { defer fmt.Println("cleanup"); panic("broken invariant") }func boundary() { defer func() { if r := recover(); r != nil { fmt.Println("recovered:", r) } }() fail() fmt.Println("unreachable")}func main() { boundary() fmt.Println("caller continues")}fail panics, then its cleanup runs. The boundary’s deferred function recovers, and boundary returns to its caller; execution does not resume at the panic site or after fail(). Without recovery, an unrecovered panic terminates the program after unwinding that goroutine. Other goroutines cannot recover this panic.
Expected output:
cleanuprecovered: broken invariantcaller continuesReturn an ordinary validation error
package main
import ( "errors" "fmt")
func readCount(n int) (int, error) { if n < 0 { return 0, errors.New("negative count") } return n, nil}func main() { _, err := readCount(-1) fmt.Println(err) n, err := readCount(3) fmt.Println(n, err == nil)}Invalid input is expected and should be handled with an error return. Reserve panic for exceptional situations where normal continuation is not appropriate. Recover does not catch all fatal runtime conditions, and os.Exit skips deferred calls. With Go 1.21+ default behavior, panic(nil) produces a non-nil runtime panic value; older semantics and GODEBUG=panicnil=1 differ. Avoid panic(nil).
Expected output:
negative count3 trueTry it locally
Write a function demo that defers a closure calling recover directly and prints "caught" if the recovered value is non-nil. Panic with "test" inside demo, then print "done" in main after demo returns.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 10: Distinguish panic, recover and ordinary errors
Check the lesson objective before moving on.
Where must recover be called to stop the ordinary panic?
What should a function normally use for invalid user input?