BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Panic and Recover

Go 1.23

Understand Panic and Recover, Go's mechanism for handling exceptional, unrecoverable errors. This example shows how to trigger a panic and how to use `defer` and `recover` to gracefully regain control of a panicking goroutine.

Code

package main

import "fmt"

func main() {
    // Defer a function to handle the panic
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered. Error:
", r)
        }
    }()

    fmt.Println("Calling panic...")
    mayPanic()
    fmt.Println("After panic (this won't run)")
}

func mayPanic() {
    panic("a problem")
}

Explanation

A panic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn't occur during normal operation, or that we aren't prepared to handle gracefully.

Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. During normal execution, a call to recover will return nil and have no other effect. If the current goroutine is panicking, a call to recover will capture the value given to panic and resume normal execution.

When to use panic/recover:

  • For truly unrecoverable errors (e.g., corrupted config)
  • Inside libraries to catch internal errors but return standard errors to users
  • Rarely for normal control flow (use error return values instead)

Code Breakdown

7-11
This deferred anonymous function will run when main exits, even if it exits due to a panic. Inside, we call recover() to check if a panic occurred.
14
Calling a function that triggers a panic. Execution of main stops here, and deferred functions begin to run.
19
The panic built-in function stops the ordinary flow of control and begins panicking. It accepts any value (usually a string or error).