0Pricing
Go Academy · Lesson

panic, recover and defer

When to panic and how to recover gracefully

What Is panic?

panic stops normal execution of the current goroutine, unwinds the call stack running deferred functions, and crashes the program if not recovered:

package main
import "fmt"

func mustPositive(n int) int {
    if n <= 0 {
        panic(fmt.Sprintf("mustPositive: got %d", n))
    }
    return n
}

func main() {
    fmt.Println(mustPositive(5))  // 5
    // fmt.Println(mustPositive(-1)) // panics!
}

When to Use panic

Use panic only for:

  • Truly unrecoverable programmer errors (broken invariants)
  • Impossible conditions that indicate a bug
  • Startup failures (missing config, failed connections during init)

Never use panic for expected failure conditions — use error instead.

All lessons in this course

  1. The error Interface
  2. Creating Custom Errors
  3. Error Wrapping and Unwrapping
  4. panic, recover and defer
← Back to Go Academy