Panic and recover
Context
Section titled “Context”panicstops normal execution, runs deferred functions, then terminates the program. It is used for unrecoverable errors.recoverregains control after a panic. It must be called inside a deferred function. If the program is panicking,recoverreturns the panic value; otherwise it returnsnil.
Example
Section titled “Example”Catch a panic and prevent program termination.
Code example
Section titled “Code example”package main
import "fmt"
func mayPanic() { panic("something went wrong")}
func main() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }()
fmt.Println("Before panic") mayPanic() fmt.Println("This line will not be executed")}Output
Section titled “Output”Before panicRecovered from panic: something went wrong