Panic and Recover

While Go has panic and recover mechanisms, they should not be used for regular error handling. They are intended for truly unrecoverable situations.

What is Panic?

Calling panic() immediately stops the execution of the current function, runs any deferred functions, and then crashes the program with a stack trace.

func critical() {
    panic("unrecoverable disaster!")
}

What is Recover?

recover() can be used inside a deferred function to “catch” a panic and prevent the program from crashing.

defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered from:", r)
    }
}()

Best Practices

  • Do not use panic/recover like try/catch. Go’s explicit error handling (if err != nil) is the correct way to handle expected failures.
  • Use log.Fatal: If your program truly cannot continue (e.g., it can’t connect to its database on startup), use log.Fatal to log the error and exit cleanly.
  • Stay explicit: Keeping errors as values makes your code more predictable and easier to debug.