Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 147 ยท Errors

panic and recover

Learn what panic does in Go, which runtime errors cause panics, how recover works inside deferred functions, when to re-panic, how to turn panics into errors, and how os.Exit and log.Fatal differ.

Most things that go wrong in a Go program are errors: expected, ordinary failures that functions return as values. But a few situations are different. An index is out of range because of a bug, a nil map is written to, or a program discovers that one of its basic assumptions is false. For these Go has panic: a built-in way to abort the current flow of execution, run deferred calls on the way out, and, unless something stops it, crash the program with a stack trace.

The companion built-in recover can stop a panic, but only in specific places and only for good reasons. This lesson explains what a panic is, which operations trigger them, how recover works (and why it only works inside a deferred function), how to turn panics into errors at the edges of a program, and how os.Exit and log.Fatal differ. Reading defer first helps, because the two features are tightly linked.

What panic does

Calling panic(value) immediately stops the normal execution of the current function. Then:

  1. Deferred functions of the current function run, in last-in, first-out order.
  2. The function returns to its caller, but not normally: the caller's deferred functions run next, and so on up the stack.
  3. When the top of the goroutine's stack is reached, the program prints panic: <value> and a goroutine trace, then exits with status 2.
Go A panic unwinds the stack and runs deferred calls (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output shows start, then the three deferred messages from the innermost function outwards, and finally the crash: panic: something is badly wrong, a blank line, goroutine 1 [running]: and the trace. The two lines after each panic or call are never reached.

The argument can be any value, but it is almost always a string or an error. For a string, the runtime prints it as is; for an error, it prints the result of Error(). Values of other types are printed in a debug format, with the type: panic: main.T{...}.

Run-time panics

You rarely call panic yourself. Most panics come from the runtime when a program does something illegal. Each of them has a distinctive message worth recognizing. The helper below calls a function, catches a panic and prints it, so we can look at several in one run (recover is explained in the next section):

Go The most common run-time panics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

All the runtime failures implement runtime.Error (an interface that extends error), while panic("custom") carries a plain string. (Two of the messages, the nil-map write and the closed channel, come without the runtime error: prefix; that is simply how the runtime words them.) Reading nil maps is fine; writing to one panics. Indexing a nil slice panics, but len(s) and append(s, x) work. A type assertion with a single result panics when it fails, which is why you should use the two-value form v, ok := i.(int) unless the type is certain.

Integer division by zero panics, but floating-point division does not: 1.0 / zero for a float variable gives +Inf. Integer overflow never panics; it wraps around.

recover

recover() stops a panic in progress and returns the value that was passed to panic. If there is no panic, it returns nil. It is only effective when called directly by a deferred function, which is why it always appears inside defer func() { ... }():

Go Catching a panic with recover

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

After the recovery, the function returns normally to its caller with whatever the named results contain. That is why the example uses a named result: a deferred function is the only code that runs after the panic in that function, and changing the result variable is the way to hand a value back.

Where recover works and where it does not

recover returns nil if it is called anywhere other than directly in a function that defer invoked: not in the normal flow of the function, and not in a helper that the deferred function calls:

Go recover outside a deferred function does nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first two lines show recover() returning nil when nothing is wrong and boom 1 being caught. In deferHelper, recover is one call level too deep, so it returns nil, the panic carries on, and the program crashes with panic: boom 2 after running main's deferred call. A related detail: defer recover() (deferring recover itself) also does nothing useful. Always wrap it in a function literal.

Re-panicking

Recovering a panic you do not understand hides bugs. A well-behaved handler recovers only the panics it expects and lets the rest continue, by calling panic again with the same value:

Go Recover what you expect, re-panic the rest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The expected parseFailure becomes an ordinary error. The nil-map write is re-panicked and eventually caught by main's own deferred function, which reports it. In real programs the last handler would log the stack and exit.

Converting panics into errors at boundaries

Panics should not cross the boundaries of a package or a goroutine as a surprise. The usual place for recover is at a boundary: where you call code that you do not control or that might have a bug, and one failing task must not take down everything else. The classic example is a web server, where a bug in one request handler should produce a 500 response, not stop the server. (Go's net/http package does this for you, and logs the panic.)

A small helper that converts a panic into an error:

Go A boundary helper that turns panics into errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

All four jobs ran, even though two of them panicked. The protect helper also keeps the original error value via %w when the panic was an error, so callers can still use errors.Is and errors.As (Wrapping and Inspecting Errors).

A panic in a goroutine cannot be recovered by another goroutine. If a goroutine you started panics and has no deferred recover of its own, the whole program crashes. Every goroutine that runs code which might panic needs its own defer/recover. You will meet goroutines in Goroutines.

When to panic

The Go guideline is blunt: use errors for expected problems, panics for programmer mistakes. Good reasons to call panic:

  • A broken invariant that can never happen if the code is correct: default: panic("unreachable") in a switch that covers every case.
  • Failed initialization of something the program cannot run without, where an error return would just be fatal anyway.
  • A "Must" helper for values known at compile time: regexp.MustCompile, template.Must. They wrap a function returning an error and panic instead, so you can write package-level variables.
Go The Must pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Never use panics as a substitute for returning errors, and do not use them for control flow ("throwing" through many levels of a program) in code other people call. A few packages do so internally, for example a recursive-descent parser may panic on a syntax error and recover at its public entry point, but the panic never escapes the package.

panic(nil)

Go 1.21 changed panic(nil): in a module whose go.mod says go 1.21 or newer, the runtime turns it into a *runtime.PanicNilError, so if r := recover(); r != nil reliably detects every panic. Older code, and programs without a go.mod such as the single files in our editor, keep the old behaviour: recover returns nil, and the panic looks as if nothing happened.

Go panic(nil) without a go.mod keeps the old behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The //go:debug directive switches a single program to the modern behaviour. A module with a recent go line gets it automatically:

Go panic(nil) with the modern setting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first run prints recovered: <nil> (<nil>), the second recovered: runtime error: panic called with nil argument (*runtime.PanicNilError). Never call panic(nil) yourself; panic with an error or a message.

os.Exit and log.Fatal

Two other ways to stop a program look similar but behave differently:

  • os.Exit(code) terminates immediately, with that status. Deferred functions do not run, and no stack trace is printed. A status of 0 means success.
  • log.Fatal(...) (and log.Fatalf, log.Fatalln) prints a message through the logger and then calls os.Exit(1), so defers are skipped as well.
Go os.Exit skips deferred calls (exits early on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Use os.Exit and log.Fatal only in main (or near it), after cleanup you control is done. A common structure is a run() error function that returns errors normally, with a tiny main:

Go
func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
}

All the defers inside run complete before main exits. Calling log.Fatal deep inside a library is a bad idea: it makes the code impossible to test and ends the caller's program without giving it a say. Likewise, log.Panic logs and then panics; it is mostly useful in the same situations as panic.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to deferred functions when a function panics?

    Deferred calls run during a panic, which is why recover is placed in a deferred function and why cleanup code still executes.
  2. 2. Where must recover() be called to stop a panic?

    recover only works when called directly by a deferred function. In normal flow, or one call level deeper, it returns nil.
  3. 3. Which of these causes a run-time panic?

    Reading a missing key returns the zero value, append works on a nil slice, and float division by zero gives Inf. Writing to a nil map panics.
  4. 4. What does os.Exit(1) do to deferred functions?

    os.Exit ends the process immediately, without running deferred calls. The same is true for log.Fatal, which calls os.Exit(1).
  5. 5. Another goroutine starts a goroutine that panics without any recover. What happens?

    A panic cannot be recovered across goroutines. An unrecovered panic in any goroutine terminates the entire program, so each goroutine needs its own recover where needed.

Summary

  • panic aborts normal execution, runs deferred calls while unwinding, and crashes the program with a stack trace and exit status 2 unless recovered.
  • Common run-time panics: nil map write, index or slice out of range, nil pointer dereference, integer divide by zero, failed single-value type assertion, closing a closed channel.
  • recover() returns the panic value, but only when called directly inside a deferred function; otherwise it returns nil. Use named results to hand a value back after recovering.
  • Recover only what you expect and re-panic the rest. Convert panics into errors at boundaries such as a request handler or a worker goroutine, which needs its own recover.
  • Use errors for expected failures, panics for programmer mistakes and Must helpers for compile-time constants.
  • os.Exit and log.Fatal end the process without running defers; keep them in main.

Next: Error Handling Patterns collects practical techniques for logging, retrying and reducing if err != nil boilerplate.