BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Panic and Recover

Go 1.23

Handle unexpected errors and prevent program crashes. This example shows how to trigger a panic and use `recover()` within a deferred function to regain control and handle the error gracefully.

Code

package main

import "fmt"

func main() {
    // Recover must be called within a deferred function
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered. Error:", r)
        }
    }()

    mayPanic()

    // This code will not run because mayPanic panics
    fmt.Println("After mayPanic()")
}

func mayPanic() {
    fmt.Println("About to panic")
    panic("a problem")
}

Explanation

A panic in Go is similar to an exception in other languages: it stops the ordinary flow of control and begins unwinding the stack. When a function panics, its execution stops, any deferred functions are executed, and then the panic propagates up to its caller. This continues until the program crashes with a stack trace or the panic is handled by recover.

recover is a built-in function that regains control of a panicking goroutine. It is only useful inside deferred functions. During normal execution, recover returns nil and does nothing. If the current goroutine is panicking, recover captures the value passed to panic and resumes normal execution from that point (the function where defer was called returns normally).

Best practices:

  • Use panic only for unrecoverable errors (e.g., programmer errors, invalid state) that simply shouldn't happen.
  • Use error return values for expected error conditions (e.g., file not found, network timeout).
  • Always check if recover() returns non-nil to verify a panic actually occurred.

Code Breakdown

7
We declare a deferred anonymous function. This is the only place where recover() works effectively. If main() panics later, this function will run before the program exits.
8
Calling recover(). If the program is panicking, "r" will contain the panic value ("a problem"). If not, "r" is nil. We check "r != nil" to handle the error.
13
Calling mayPanic(). This function will trigger a panic.
21
The panic("a problem") statement stops mayPanic immediately. Control jumps to the deferred function in main. The line "fmt.Println("After mayPanic()")" in main is never reached.