Go by Example

Panic

Use panic for unrecoverable program errors and return errors for expected failures.

A panic is Go's term for an unexpected failure that stops normal work in the current goroutine, a function running while its caller continues. Go first runs deferred cleanup functions. If none stops the panic, the program exits and prints a stack trace, a list of function calls that led to the failure. Use returned errors for problems the caller is expected to handle.

The deferred calls run in last-in, first-out order before the panic is reported.

package main
 
import "fmt"
 
func main() {
    defer fmt.Println("first defer")
    defer fmt.Println("second defer")
    fmt.Println("before panic")
    panic("unexpected state")
}

In production

Use panic only when the program reaches a state that should be impossible because of a programming mistake. Invalid input, missing files and network failures are expected problems, so return them as errors. A panic that is not recovered in any goroutine stops the whole program.

Enjoyed this? Get more software craft delivered to your inbox.