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.

Tiny Practice

Starter scenario

Choose the normal mechanism for a missing user file: panic or returned error.

Go code

choice := "CHANGE_ME"
fmt.Println(choice)
Line-by-line explanation
  1. The answer is stored as text.
  2. Replace CHANGE_ME.
Expected output
(complete the starter first)

The starter intentionally contains CHANGE_ME.

Hint
  1. A missing file is expected.
  2. Go functions usually return errors.
  3. Do not choose panic.
Show Solution

Go code

choice := "returned error"
fmt.Println(choice)
Line-by-line explanation
  1. The string states the normal mechanism.
  2. Println displays it.
Expected output
returned error

This is the expected result.