Panic and recover
Context
Section titled “Context”panicstops normal execution, runs deferred functions, then the program terminates.recoveris a built‑in function that regains control after apanic. It must be called inside a deferred function.
Use only for unrecoverable errors (e.g., inconsistent state). For normal errors, prefer the error return pattern.
Example
Section titled “Example”Catch a panic and continue.
Code example
Section titled “Code example”package main
import "fmt"
func main() { // Function that may panic defer func() { if r := recover(); r != nil { fmt.Println("Recovered from:", r) } }()
fmt.Println("Before panic") panic("a serious error") fmt.Println("This will not be executed")}Output
Section titled “Output”Before panicRecovered from: a serious errorThe program does not crash; it continues after recover. This can be useful for web servers (prevent a single request from crashing the whole server).