Skip to content

Panic and recover

  • panic stops normal execution, runs deferred functions, then terminates the program. It is used for unrecoverable errors.
  • recover regains control after a panic. It must be called inside a deferred function. If the program is panicking, recover returns the panic value; otherwise it returns nil.

Catch a panic and prevent program termination.

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")
}
Terminal window
Before panic
Recovered from panic: something went wrong