liveBook · Manning

Panic

As explained in 100 Go Mistakes and How to Avoid Them

panic is a Go built-in function or runtime state that stops normal execution and begins unwinding the current goroutine's call stack.

A common mistake is treating panic as Go's everyday exception mechanism. panic stops ordinary execution, unwinds the current goroutine's call stack, and either terminates that goroutine or reaches recover. section 7.1

func main() {
    fmt.Println("a")
    panic("foo")
    fmt.Println("b")
}

A minimal program prints a, panics, and never reaches the following print statement. section 7.1

Trace panic behavior through these rules:

  • A panic moves upward through the current call stack until the goroutine returns or a deferred function recovers it. section 7.1
  • recover is useful only inside a defer function; elsewhere it returns nil and has no other effect. section 7.1
  • Use panic sparingly for unrecoverable conditions, such as programmer errors or failure to load a mandatory dependency; return ordinary errors otherwise. section 7.1 section 7.8

Recovering at a boundary

A deferred function can call recover while f panics, print the recovered value, and allow main's goroutine to continue. This is a targeted containment mechanism, not a replacement for returning errors. section 7.1

func checkWriteHeaderCode(code int) {
    if code < 100 || code > 999 {
        panic(fmt.Sprintf("invalid WriteHeader code %v", code))
    }
}

An invalid HTTP status code is treated as a programmer error and triggers panic rather than an ordinary returned error. section 7.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains control-flow unwinding, deferred recovery, and appropriate use, stopping short of broader runtime internals.
Examples
Uses print-before-panic code, deferred recovery, invalid HTTP status validation, and duplicate or nil database-driver registration.
What it assumes
Builds on Go functions, goroutines, deferred functions, and the convention of returning an error as the last result.
What you can do after
Evaluate/understand when to panic, recover a panic in deferred code, and choose ordinary error returns for expected failures.
How it connects
Connects panic with error handling, recover, defer, goroutines, call stacks, programmer errors, and mandatory dependencies.

Also explained in

Compare how 8 books explain panic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.