Skip to main content

Overview

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.
Unlike some languages which use exceptions for handling many errors, in Go it is idiomatic to use error-indicating return values wherever possible. Use panic sparingly.

When to Use Panic

Panic should be reserved for exceptional situations:
  • Unrecoverable errors during initialization
  • Programming errors that indicate bugs
  • Situations where continuing would be dangerous
  • Errors that “should never happen”

Basic Panic Usage

The simplest use of panic is with a string message:
func main() {
    // This will cause the program to panic and exit
    panic("a problem")
    
    // Code after panic is never executed
    fmt.Println("This won't print")
}

Panic on Unexpected Errors

A common use of panic is to abort if a function returns an error value that we don’t know how to (or want to) handle:
path := filepath.Join(os.TempDir(), "file")
_, err := os.Create(path)
if err != nil {
    panic(err)
}
This pattern is useful during development or in situations where an error truly indicates a programming bug rather than a runtime condition.

Complete Example

package main

import (
	"os"
	"path/filepath"
)

func main() {
	// We'll use panic throughout this site to check for
	// unexpected errors. This is the only program on the
	// site designed to panic.
	panic("a problem")

	// A common use of panic is to abort if a function
	// returns an error value that we don't know how to
	// (or want to) handle. Here's an example of
	// panicking if we get an unexpected error when creating a new file.
	path := filepath.Join(os.TempDir(), "file")
	_, err := os.Create(path)
	if err != nil {
		panic(err)
	}
}

Output

Running this program will cause it to panic, print an error message and goroutine traces, and exit with a non-zero status:
$ go run panic.go
panic: a problem

goroutine 1 [running]:
main.main()
	/.../panic.go:12 +0x47
...
exit status 2
When the first panic in main fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment the first panic out.

What Happens During a Panic

When a function panics:
  1. Execution stops - The function stops executing immediately
  2. Deferred functions run - Any deferred functions are executed in reverse order
  3. Stack unwinds - The panic bubbles up the call stack
  4. Program terminates - Unless recovered, the program crashes with a stack trace
func example() {
    defer fmt.Println("This runs even during panic")
    panic("something went wrong")
    fmt.Println("This never runs")
}

Panic vs Errors

Use Errors for

  • Expected failure conditions
  • Recoverable problems
  • Validation failures
  • Network/IO issues
  • User input errors

Use Panic for

  • Programming bugs
  • Impossible situations
  • Initialization failures
  • Critical system errors
  • Unrecoverable states

Best Practices

Go’s philosophy is to use explicit error return values for all expected error conditions. Reserve panic for truly exceptional situations.
// Bad: using panic for validation
func divide(a, b int) int {
    if b == 0 {
        panic("division by zero") // Don't do this
    }
    return a / b
}

// Good: returning an error
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}
It’s acceptable to panic during init() or package initialization if the library cannot function without certain preconditions.
func init() {
    if err := loadConfig(); err != nil {
        panic(fmt.Sprintf("failed to load config: %v", err))
    }
}
Use panic to catch bugs during development, such as invalid function arguments that should never happen in correct code.
func processValue(val int) {
    if val < 0 {
        panic("negative values are not supported")
    }
    // ... process value
}

Defer

Learn how deferred functions interact with panic.

Recover

Discover how to recover from panics gracefully.

Build docs developers (and LLMs) love