Go · Stage 8 – Errors and Files · Lesson 50 of 64

Panics and recover

Recognize panics and reserve recovery for exceptional boundaries.

Go code

panic("unexpected state")
Line-by-line explanation
  1. Panic is called with a message.
  2. Normal execution stops.
  3. Go prints a stack trace.
Expected output
panic: unexpected state

Additional stack-trace lines normally follow.

Use returned errors for expected failures such as invalid input or missing files. Do not use panic as a replacement for if err != nil.