SyntaxPilot
Courses/Go Programming/Lesson 26

Go Programming · Lesson 26 of 89 · 10 min

panic and recover

panicstack unwindingrecoverdeferred recover patternruntime panics (index out of range, nil map write, nil dereference, type assertion failure)Must functions (regexp.MustCompile)unrecovered panic in a goroutine crashes the programwhen panicking is acceptable

These are the notes for Go episode 26. Episode 25 drew a line: errors are for failures you expect (a missing file, bad input), panics are for bugs. This episode shows what really happens when a Go program panics: normal execution stops, the call stack unwinds while every deferred call still runs, and if nobody stops it the program prints a stack trace and exits with status 2. You will call panic yourself, discover why calling recover directly does nothing, and invent the deferred recover pattern that turns a panic into an ordinary error with a named result. You will meet the common runtime panics (index out of range, nil map write, nil pointer dereference, failed type assertion, integer divide by zero), see why Must functions like regexp.MustCompile panic on purpose, watch an unrecovered panic in a goroutine crash the whole program, and learn when panicking is acceptable. The mini project keeps an order counter running when one order hits a bug, the way Go's own web server does for each request. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs, compiler errors and panics are from real runs of go run main.go (Go 1.24, linux/amd64). Panic traces show /tmp/.../main.go where the real temporary folder was, and the +0x... numbers and goroutine numbers can differ between machines and runs.

The problem: a real crash

A billing program. itemAt returns item number i of an order. The order has three items. We ask for item 0, which is fine, and then, because of a bug somewhere, item 5.

package main

import "fmt"

func itemAt(order []string, i int) string {
    return order[i]
}

func main() {
    order := []string{"chai", "samosa", "vada pav"}
    fmt.Println("first:", itemAt(order, 0))
    fmt.Println("sixth:", itemAt(order, 5))
    fmt.Println("next customer, please")
}
first: chai
panic: runtime error: index out of range [5] with length 3

goroutine 1 [running]:
main.itemAt(...)
    /tmp/.../main.go:6
main.main()
    /tmp/.../main.go:12 +0xd7
exit status 2

Read it line by line:

  • first: chai: the first call worked.
  • panic: runtime error: index out of range [5] with length 3: the panic message. Index 5 was asked for; the slice only has 3 elements (indexes 0, 1, 2).
  • goroutine 1 [running]:: which goroutine (a function running independently; main runs in goroutine 1) was running. More on goroutines below.
  • main.itemAt(...) / main.go:6, then main.main() / main.go:12: the functions that were active, innermost first, with file and line. This list is a stack trace.
  • exit status 2: the program ended with exit code 2, which go run reports. A program that finishes normally exits with 0.
  • next customer, please never printed.

Why Go stops: reading item 5 of 3 has no sensible answer. If the program carried on with some random value, the bill would be garbage, silently. So Go stops, loudly, and tells you exactly where. That stop is a panic.

What is a panic?

In a factory In Go Name
Someone hits the emergency stop: something is badly wrong normal execution stops panic
Machines shut down safely, one by one, back to front each function returns and its deferred calls run stack unwinding
An incident report: what happened and where message + functions + line numbers stack trace

The call stack

  • The call stack is the pile of functions running right now. main calls serve, serve calls cook: each call goes on top of the pile, like plates. When a function returns, its plate comes off.
  • When cook panics, Go goes back down the pile: cook stops, then serve, then main. This is stack unwinding.
  • On the way, each function's deferred calls run (episode 10: defer schedules a call for when the function exits), last in, first out (LIFO).
  • If nobody recovers, the program prints the panic message and the stack trace, and exits with status 2.

Stack unwinding, live

You can panic yourself by calling the built-in function panic(v) with any value v, usually a message string. cook panics if there's no dosa batter. Every function defers one clean-up line.

package main

import "fmt"

func cook(dish string) {
    defer fmt.Println("cook: clean the stove")
    if dish == "dosa" {
        panic("no dosa batter")
    }
    fmt.Println("cook: made", dish)
}

func serve(dish string) {
    defer fmt.Println("waiter: clear the table")
    cook(dish)
    fmt.Println("waiter: served", dish)
}

func main() {
    defer fmt.Println("main: close the shop")
    serve("chai")
    serve("dosa")
    fmt.Println("main: done")
}
cook: made chai
cook: clean the stove
waiter: served chai
waiter: clear the table
cook: clean the stove
waiter: clear the table
main: close the shop
panic: no dosa batter

goroutine 1 [running]:
main.cook({0x4b4c73?, 0xc000062028?})
    /tmp/.../main.go:8 +0xde
main.serve({0x4b4c73, 0x4})
    /tmp/.../main.go:15 +0x66
main.main()
    /tmp/.../main.go:22 +0x76
exit status 2
  • Chai goes normally: made, clean the stove (cook's defer), served, clear the table (serve's defer).
  • Dosa panics inside cook. Then: cook: clean the stove, waiter: clear the table, main: close the shop. Every deferred clean-up ran, from the top of the stack down.
  • cook: made dosa, waiter: served dosa and main: done never printed: the normal code after the panic was skipped.
  • Only then does Go print panic: no dosa batter and the stack trace: cook, called by serve, called by main.
  • This is why defer is the right place for clean-up like closing a file or unlocking something: it runs even during a panic.

recover

One bad dish shouldn't close the whole shop. Go has a built-in function recover(): it stops a panic and returns the panic value (whatever was passed to panic). Let's call it at the start of main, then serve a dosa.

package main

import "fmt"

func serve(dish string) {
    if dish == "dosa" {
        panic("no dosa batter")
    }
    fmt.Println("served", dish)
}

func main() {
    r := recover()
    fmt.Println("recovered:", r)
    serve("dosa")
    fmt.Println("next customer, please")
}
recovered: <nil>
panic: no dosa batter

goroutine 1 [running]:
main.serve({0x4b3c6f?, 0xc000062028?})
    /tmp/.../main.go:7 +0x98
main.main()
    /tmp/.../main.go:15 +0x6f
exit status 2
  • recovered: <nil>, then the crash anyway.
  • Why: when we called recover, nothing was panicking yet, so it returned nil. And once the panic starts, main's normal code doesn't run any more, so nobody calls recover again.
  • The only code that still runs during a panic is deferred code. So recover must be called from a deferred function.

The deferred recover pattern

Put recover inside a deferred function. safeServe defers an anonymous function (a function literal with no name, episode 10) that calls recover. If the result r is not nil, there was a panic, and we turn it into an error. err is a named result (episode 9), so the deferred function can still set it after the panic, and that's the value the caller receives.

package main

import "fmt"

func serve(dish string) {
    if dish == "dosa" {
        panic("no dosa batter")
    }
    fmt.Println("served", dish)
}

func safeServe(dish string) (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("serve %s: panic: %v", dish, r)
        }
    }()
    serve(dish)
    return nil
}

func main() {
    for _, d := range []string{"chai", "dosa", "samosa"} {
        if err := safeServe(d); err != nil {
            fmt.Println("error:", err)
        }
    }
    fmt.Println("shop still open")
}
served chai
error: serve dosa: panic: no dosa batter
served samosa
shop still open
  • Chai served. Dosa: the panic stopped at safeServe, became an ordinary error, and main printed it. Samosa served. Shop still open.
  • You just invented the deferred recover pattern: defer + recover + a named result = a panic becomes an error.

The three rules of recover

  1. recover only stops a panic when it is called directly by a deferred function. Called anywhere else (normal code, or a helper that the deferred function calls), it returns nil. See the expert corner.
  2. When there is no panic, recover returns nil. That's why the pattern checks if r := recover(); r != nil.
  3. recover only catches panics in its own goroutine (see below).

After a successful recover, the function that deferred the call returns normally to its caller, with whatever its named results hold.

Runtime panics

Now that we can catch panics, let's meet the common ones. try runs a function and prints whatever recover returns. %-10s pads the label to 10 characters so the column lines up.

package main

import "fmt"

func try(name string, f func()) {
    defer func() {
        fmt.Printf("%-10s %v\n", name+":", recover())
    }()
    f()
}

type Order struct{ Qty int }

func main() {
    s := []int{1, 2, 3}
    i := 5
    try("index", func() { _ = s[i] })

    var stock map[string]int
    try("nil map", func() { stock["chai"] = 10 })

    var o *Order
    try("nil ptr", func() { o.Qty++ })

    var x any = "two"
    try("assert", func() { _ = x.(int) })

    n := 0
    try("divide", func() { _ = 10 / n })
}
index:     runtime error: index out of range [5] with length 3
nil map:   assignment to entry in nil map
nil ptr:   runtime error: invalid memory address or nil pointer dereference
assert:    interface conversion: interface {} is string, not int
divide:    runtime error: integer divide by zero

These are runtime panics: the Go runtime (the part of Go that runs alongside your program: memory, goroutines, bounds checks) raises them when your code does something impossible. Every one means a bug to fix, not something to hide with recover.

Panic Typical cause Fix
index out of range [5] with length 3 indexing past the end of a slice, array or string check i < len(s) first
assignment to entry in nil map writing to a map declared with var m map[K]V but never made (episode 15) m := make(map[string]int) or a literal
invalid memory address or nil pointer dereference using a field or method through a nil pointer (episode 11) check p != nil, or make the value
interface conversion: interface {} is string, not int a type assertion x.(int) without comma-ok, on the wrong type (episode 22) v, ok := x.(int)
integer divide by zero integer / or % by a variable that is 0 check the divisor; return an error

Notes:

  • We used variables (i := 5, n := 0) on purpose. With constants, s[5] on a known-length array or 10 / 0 is caught by the compiler, before the program runs.
  • Reading from a nil map is fine (it returns the zero value); only writing panics.
  • Floating-point division by zero does not panic: 1.0 / zero gives +Inf.

Must functions

Sometimes the standard library panics on purpose. regexp is Go's regular expression package. A regular expression is a pattern that describes text: ^[6-9][0-9]{9}$ means "start, one digit from 6 to 9, then exactly nine more digits, end": an Indian mobile number. The backquotes make a raw string literal (episode 17), so backslashes and brackets are taken literally.

  • regexp.Compile(pattern) checks the pattern and returns (*regexp.Regexp, error).
  • regexp.MustCompile(pattern) is the same, but panics instead of returning an error. By convention, a function named MustX panics on failure.
package main

import (
    "fmt"
    "regexp"
)

// Must functions panic instead of returning an error

func main() {
    phone := regexp.MustCompile(`^[6-9][0-9]{9}$`)
    fmt.Println(phone.MatchString("9876543210"), phone.MatchString("12345"))

    _, err := regexp.Compile(`[0-9`)
    fmt.Println("Compile:", err)

    regexp.MustCompile(`[0-9`)
    fmt.Println("never printed")
}
true false
Compile: error parsing regexp: missing closing ]: `[0-9`
panic: regexp: Compile(`[0-9`): error parsing regexp: missing closing ]: `[0-9`

goroutine 1 [running]:
regexp.MustCompile({0x4d7c32, 0x4})
    /usr/local/go1.24.7/src/regexp/regexp.go:313 +0xb4
main.main()
    /tmp/.../main.go:17 +0x19b
exit status 2
  • true false: 9876543210 matches; 12345 doesn't.
  • Compile returns an error for the broken pattern [0-9 (a bracket that's never closed).
  • MustCompile panics with the same message.

Why is panicking OK here? The pattern is written in your source code. If it's broken, that's a programmer's bug, and you want to find out the very first time the program runs, not write if err != nil for something that can never succeed. That's why MustCompile is usually used for package-level variables:

var phone = regexp.MustCompile(`^[6-9][0-9]{9}$`) // checked once, at start-up

Use regexp.Compile (with error handling) when the pattern comes from a user or a file.

Panics in goroutines

A goroutine is a function running at the same time as the rest of your program. You start one with the keyword go in front of a call: go deliver("chai"). The concurrency part of this course covers them properly; here we need just one fact. time.Sleep(100 * time.Millisecond) pauses main for a tenth of a second so the goroutine gets a chance to run.

package main

import (
    "fmt"
    "time"
)

func deliver(dish string) {
    panic("bike broke down with " + dish)
}

func main() {
    defer func() {
        fmt.Println("main recovered:", recover())
    }()
    go deliver("chai")
    time.Sleep(100 * time.Millisecond)
    fmt.Println("main: done")
}
panic: bike broke down with chai

goroutine 6 [running]:
main.deliver(...)
    /tmp/.../main.go:9
created by main.main in goroutine 1
    /tmp/.../main.go:16 +0x3b
exit status 2
  • The whole program crashed. main recovered: never printed: main's deferred recover never got the panic.
  • The trace says goroutine 6, created by main.main in goroutine 1: the panic happened on a different goroutine's stack.
  • Each goroutine has its own call stack, and recover only catches panics on its own stack. An unrecovered panic in any goroutine ends the entire program.

The fix: recover inside the goroutine.

package main

import (
    "fmt"
    "time"
)

func deliver(dish string) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("delivery recovered:", r)
        }
    }()
    panic("bike broke down with " + dish)
}

func main() {
    go deliver("chai")
    time.Sleep(100 * time.Millisecond)
    fmt.Println("main: done")
}
delivery recovered: bike broke down with chai
main: done

Every goroutine that might panic needs its own deferred recover. (Real code waits for goroutines with sync.WaitGroup or channels instead of time.Sleep: see practice question 4.)

When is it OK to panic?

Situation Panic? Why
Something that "can never happen" happened yes it's a bug; carrying on would spread wrong data
Setup written in the source is broken (MustCompile, templates) yes found the first time the program runs
The program can't even start (required setting missing in main) acceptable nothing useful can run; many programs print an error and os.Exit(1) instead
Bad user input, missing file, slow network no expected failures: return an error
A library's public functions no don't let a panic escape to callers; recover inside and return an error

Mini project: survive a bad order

An order counter that keeps running when one order hits a bug. count has a bug: it assumes there's a quantity for every item. handle wraps count with the deferred recover pattern and turns a panic into an error carrying the order number. type Order struct{ ID int; Items []string; Qty []int } is written on one line with semicolons so the program fits on screen.

package main

import "fmt"

type Order struct{ ID int; Items []string; Qty []int }
func count(o Order) int {
    total := 0
    for i := range o.Items {
        total += o.Qty[i] // bug: Qty may be shorter
    }
    return total
}

func handle(o Order) (n int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("order %d: %v", o.ID, r)
        }
    }()
    return count(o), nil
}

func main() {
    orders := []Order{
        {1, []string{"chai", "samosa"}, []int{2, 3}},
        {2, []string{"chai", "dosa"}, []int{1}},
        {3, []string{"vada pav"}, []int{4}},
    }
    for _, o := range orders {
        n, err := handle(o)
        if err != nil {
            fmt.Println("LOG:", err)
            continue
        }
        fmt.Println("order", o.ID, "items:", n)
    }
}
order 1 items: 5
LOG: order 2: runtime error: index out of range [1] with length 1
order 3 items: 4
  • Order 1: 2 + 3 = 5 items.
  • Order 2 has two items but only one quantity: count panics, handle recovers, and main logs one line with the order number.
  • Order 3: served. One bad order was logged; every other customer was served.

Go's own web server works the same way. From go doc net/http.Handler: "If ServeHTTP panics, the server (the caller of ServeHTTP) assumes that the effect of the panic was isolated to the active request. It recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM". The place where one unit of work (a request, an order, a job) starts is called a boundary, and that's where a recover belongs.

But recovering doesn't fix anything. The log tells you where the bug is.

Extended version: fix the bug, keep the safety net

count now checks and returns an error (wrapping a sentinel, episode 25). handle still recovers, as a safety net for bugs nobody has found yet.

package main

import (
    "errors"
    "fmt"
)

var ErrMismatch = errors.New("items and quantities differ")

type Order struct {
    ID    int
    Items []string
    Qty   []int
}

// count no longer panics: it checks first and returns an error.
func count(o Order) (int, error) {
    if len(o.Qty) != len(o.Items) {
        return 0, fmt.Errorf("%d items, %d quantities: %w", len(o.Items), len(o.Qty), ErrMismatch)
    }
    total := 0
    for i := range o.Items {
        total += o.Qty[i]
    }
    return total, nil
}

// handle still recovers, as a safety net for bugs we haven't found yet.
func handle(o Order) (n int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("order %d: panic: %v", o.ID, r)
        }
    }()
    n, err = count(o)
    if err != nil {
        return 0, fmt.Errorf("order %d: %w", o.ID, err)
    }
    return n, nil
}

func main() {
    orders := []Order{
        {1, []string{"chai", "samosa"}, []int{2, 3}},
        {2, []string{"chai", "dosa"}, []int{1}},
        {3, []string{"vada pav"}, []int{4}},
    }
    bad := 0
    for _, o := range orders {
        n, err := handle(o)
        if errors.Is(err, ErrMismatch) {
            bad++
            fmt.Println("LOG:", err)
            continue
        }
        fmt.Println("order", o.ID, "items:", n)
    }
    fmt.Println("bad orders:", bad)
}
order 1 items: 5
LOG: order 2: 2 items, 1 quantities: items and quantities differ
order 3 items: 4
bad orders: 1

The expected problem is now an error the program can recognise with errors.Is and count; a panic would only mean a new, unknown bug.

Expert corner

recover must be called directly by the deferred function

package main

import "fmt"

func helper() {
    fmt.Println("helper recovered:", recover())
}

func main() {
    defer func() {
        helper() // recover is NOT called directly by the deferred function
    }()
    panic("no dosa batter")
}
helper recovered: <nil>
panic: no dosa batter

goroutine 1 [running]:
main.main()
    /tmp/.../main.go:13 +0x3e
exit status 2

The deferred function calls helper, and helper calls recover. That's one call too deep: recover returns nil and the panic continues. (Deferring helper itself, defer helper(), would work, because then helper is the deferred function.)

Re-panicking: recover only what you expect

A recover that swallows every panic also hides real bugs. You can recover, look at the value, and panic again with it if it isn't yours:

package main

import "fmt"

type expected struct{ msg string }

func serve(dish string) {
    if dish == "dosa" {
        panic(expected{"no dosa batter"})
    }
    var m map[string]int
    m[dish] = 1 // a real bug
}

func safeServe(dish string) (err error) {
    defer func() {
        r := recover()
        if e, ok := r.(expected); ok {
            err = fmt.Errorf("serve %s: %s", dish, e.msg)
            return
        }
        if r != nil {
            panic(r) // not ours: let it crash
        }
    }()
    serve(dish)
    return nil
}

func main() {
    fmt.Println(safeServe("dosa"))
    fmt.Println(safeServe("chai"))
}
serve dosa: no dosa batter
panic: assignment to entry in nil map [recovered]
    panic: assignment to entry in nil map

goroutine 1 [running]:
main.safeServe.func1()
    /tmp/.../main.go:23 +0x115
panic({0x4a2d20?, 0x55f120?})
    /usr/local/go1.24.7/src/runtime/panic.go:792 +0x132
main.serve(...)
    /tmp/.../main.go:12
main.safeServe({0x4b7273?, 0xc000096020?})
    /tmp/.../main.go:26 +0x85
main.main()
    /tmp/.../main.go:32 +0x6f
exit status 2

The expected panic became an error; the nil-map bug still crashed, marked [recovered] and then re-panicked.

runtime.Error

Runtime panics carry a value that implements the interface runtime.Error (an error with an extra marker method). You can tell bugs from your own panic values:

package main

import (
    "errors"
    "fmt"
    "runtime"
)

func try(f func()) (err error) {
    defer func() {
        r := recover()
        if r == nil {
            return
        }
        if re, ok := r.(runtime.Error); ok {
            err = fmt.Errorf("bug: %w", re)
            return
        }
        err = fmt.Errorf("panic: %v", r)
    }()
    f()
    return nil
}

func main() {
    s := []int{1, 2, 3}
    i := 5
    err := try(func() { _ = s[i] })
    fmt.Println(err)
    var re runtime.Error
    fmt.Println(errors.As(err, &re))

    err = try(func() { panic("no dosa batter") })
    fmt.Println(err, errors.As(err, &re))
}
bug: runtime error: index out of range [5] with length 3
true
panic: no dosa batter false

Because we wrapped the runtime.Error with %w, errors.As finds it later (episode 25).

panic(nil)

Since Go 1.21, panic(nil) panics with a *runtime.PanicNilError, so recover never returns nil for a real panic:

package main

import "fmt"

func main() {
    defer func() {
        r := recover()
        fmt.Printf("%T: %v\n", r, r)
    }()
    panic(nil)
}
*runtime.PanicNilError: panic called with nil argument

os.Exit skips deferred calls

package main

import (
    "fmt"
    "os"
)

func main() {
    defer fmt.Println("close the shop")
    fmt.Println("serving")
    os.Exit(3)
}
serving
exit status 3

close the shop never printed. os.Exit ends the program immediately: no unwinding, no defers. A panic, by contrast, runs every defer on the way out.

What the spec says

The Go specification (section "Handling panics") describes it this way: while executing a function F, an explicit call to panic or a run-time panic terminates the execution of F; any functions deferred by F are then executed as usual; next, any deferred functions run by F's caller, and so on up to the top-level function in the executing goroutine. At that point the program is terminated and the error is reported, including the value of the argument to panic. This termination sequence is called panicking. The return value of recover is nil when the goroutine is not panicking or when recover was not called directly by a deferred function.

Common mistakes (and the real messages)

Mistake What you see Why Fix
r := recover() at the top of main recovered: <nil>, then the crash nothing is panicking yet; later, normal code doesn't run call recover inside a deferred function
recover in a helper called by the deferred function helper recovered: <nil>, crash not called directly by the deferred function defer func() { if r := recover(); r != nil {...} }()
setting a normal (unnamed) result in the deferred recover the caller gets zero values, no error only named results can be changed after a panic func f() (err error)
recover in main for a panic in a goroutine the whole program crashes recover is per goroutine recover inside the goroutine
s[i] with i >= len(s) panic: runtime error: index out of range [5] with length 3 no such element check the index
var m map[string]int; m["k"] = 1 panic: assignment to entry in nil map the map was never made make(map[string]int)
var o *Order; o.Qty++ panic: runtime error: invalid memory address or nil pointer dereference nil pointer check o != nil
x.(int) when x holds a string panic: interface conversion: interface {} is string, not int wrong type, no comma-ok v, ok := x.(int)
regexp.MustCompile(userInput) panic: regexp: Compile(...) Must panics on bad input regexp.Compile + if err != nil
using recover to hide bugs wrong results, no crash the bug is still there log it, then fix the code

Practice

  1. (Homework) Write safeDivide(a, b int) (int, error) that returns an error for b == 0 instead of panicking.
  2. (Homework) Write try() and trigger all five runtime panics from the video (the CATALOG program above is the solution).
  3. (Homework) Fix count() so it returns an error for missing quantities (the extended project above is the solution).
  4. (Homework) Panic inside a goroutine, recover inside it, and wait for it properly with sync.WaitGroup instead of time.Sleep.
  5. Why does a deferred recover need a named result to report an error to the caller?
Solutions
  1. Check first; no panic, no recover needed.
package main

import (
    "errors"
    "fmt"
)

var ErrDivByZero = errors.New("division by zero")

func safeDivide(a, b int) (int, error) {
    if b == 0 {
        return 0, ErrDivByZero
    }
    return a / b, nil
}

func main() {
    fmt.Println(safeDivide(100, 4))
    fmt.Println(safeDivide(100, 0))
}
25 <nil>
0 division by zero
  1. wg.Add(1) before starting, defer wg.Done() inside, wg.Wait() in main. The recover is deferred after wg.Done, so it runs first (LIFO) and Done still runs.
package main

import (
    "fmt"
    "sync"
)

func deliver(dish string, wg *sync.WaitGroup) {
    defer wg.Done()
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("delivery of", dish, "recovered:", r)
        }
    }()
    if dish == "dosa" {
        panic("bike broke down")
    }
    fmt.Println("delivered", dish)
}

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    go deliver("dosa", &wg)
    wg.Wait()
    fmt.Println("main: done")
}
delivery of dosa recovered: bike broke down
main: done
  1. After a panic, the function's return statement never runs. The deferred function runs instead, and the only way it can change what the caller receives is by assigning to the function's named result variables, which are returned when the function finishes.

Quick quiz

1. What does this print? (From the video.)

func f() (n int) {
    defer func() {
        if recover() != nil {
            n = -1
        }
    }()
    var m map[string]int
    m["a"] = 1
    return 1
}

func main() {
    fmt.Println(f())
}

A. 1 · B. -1 · C. 0 · D. it crashes

Answer

B. The nil map write panics before return 1. The deferred function recovers and sets the named result n to -1. Real output: -1.

2. In what order are the lines printed?

package main

import "fmt"

func main() {
    defer fmt.Println("A")
    defer func() {
        fmt.Println("B", recover())
    }()
    defer fmt.Println("C")
    panic("boom")
}
Answer
C
B boom
A

Defers run last in, first out. C first; then the function with recover, which stops the panic and prints its value; then A. The program exits normally.

3. What does this print before it crashes?

package main

import "fmt"

func main() {
    r := recover()
    fmt.Println(r == nil)
    defer fmt.Println("deferred")
    var p *int
    fmt.Println(*p)
}
Answer

true, then deferred, then panic: runtime error: invalid memory address or nil pointer dereference (plus a [signal SIGSEGV ...] line and the stack trace) and exit status 2. The early recover returned nil; the defer runs during unwinding but doesn't recover.

4. What does this print?

package main

import "fmt"

func f() (s string) {
    defer func() {
        recover()
    }()
    s = "before"
    panic("boom")
}

func main() {
    fmt.Printf("%q\n", f())
}
Answer

"before". The named result s was set before the panic, the deferred function recovered, and f returned normally with s as it was.

5. main has a deferred recover. A goroutine started by main panics. What happens?

Answer

The whole program crashes. recover only catches panics in its own goroutine.

Interview questions

  1. What is a panic in Go? A run-time event that stops a goroutine's normal execution, unwinds its stack running deferred calls, and, unless recovered, ends the program with the panic value, a stack trace and exit status 2. It's for bugs and impossible states.
  2. How is a panic different from an error? An error is an ordinary value returned to the caller for expected failures. A panic is for programming mistakes and stops normal execution.
  3. How do you recover from a panic? Call recover() directly inside a deferred function. It returns the panic value (nil if not panicking) and stops the panic; the function then returns normally. Use a named result to return an error.
  4. Does defer run during a panic? Does it run on os.Exit? Yes during a panic, LIFO. No on os.Exit.
  5. Name four runtime panics. Index out of range, assignment to entry in nil map, nil pointer dereference, interface conversion (failed type assertion); also integer divide by zero.
  6. What is a Must function and when is it appropriate? A function that panics instead of returning an error, like regexp.MustCompile. Appropriate when the input is fixed in the source code, typically at package level or start-up.
  7. Can main recover a panic from another goroutine? No. Each goroutine must recover its own panics; an unrecovered panic in any goroutine terminates the program.
  8. Where should a server recover? At the boundary of each unit of work, such as each request; net/http does this for handlers and logs a stack trace.
  9. Should a library panic? Not for normal failures, and it shouldn't let panics escape its public API; return errors.

Glossary

Term Meaning Example
Panic a run-time stop of normal execution, for bugs and impossible states panic: runtime error: index out of range [5] with length 3
panic(v) the built-in function that starts a panic with any value panic("no dosa batter")
Panic value the value passed to panic, returned by recover "no dosa batter"
Call stack the pile of functions running right now, newest on top main → serve → cook
Stack unwinding going back down the call stack during a panic, running each function's defers clean the stove, clear the table, close the shop
Stack trace the list of active functions with files and lines, printed on a crash main.itemAt(...) main.go:6
Exit status 2 the exit code of a program killed by an unrecovered panic exit status 2
defer schedules a call to run when the function exits, LIFO (episode 10) defer fmt.Println("close")
LIFO last in, first out: the last deferred call runs first C, B, A
recover() built-in; inside a deferred function, stops a panic and returns its value; otherwise nil if r := recover(); r != nil
Deferred recover pattern defer func(){ if r := recover(); r != nil { err = ... } }() safeServe
Named result a result variable with a name, which a deferred function can set (episode 9) func f() (err error)
Anonymous function a function literal without a name (episode 10) func() { ... }()
Runtime the part of Go that runs alongside your program (memory, goroutines, checks) raises runtime panics
Runtime panic a panic raised by the runtime for an impossible operation nil map write
runtime.Error the interface implemented by runtime panic values r.(runtime.Error)
Index out of range indexing past the end of a slice, array or string s[5] with len(s) == 3
Nil map write assigning into a map that was never made assignment to entry in nil map
Nil pointer dereference using a value through a nil pointer invalid memory address or nil pointer dereference
Type assertion failure x.(T) without comma-ok when x doesn't hold a T interface conversion: interface {} is string, not int
Integer divide by zero integer / or % by 0 at run time runtime error: integer divide by zero
Regular expression a pattern that describes text ^[6-9][0-9]{9}$
regexp.Compile checks a pattern; returns (*Regexp, error) regexp.Compile("[0-9")
Must function a function that panics instead of returning an error regexp.MustCompile
Raw string literal a backquoted string with no escape processing (episode 17) `^[0-9]+$`
Goroutine a function running at the same time as the rest of the program, started with go go deliver("chai")
go keyword starts a call in a new goroutine go deliver("chai")
time.Sleep pauses the current goroutine for a duration time.Sleep(100 * time.Millisecond)
sync.WaitGroup waits for a set of goroutines to finish wg.Add(1), wg.Done(), wg.Wait()
Unrecovered goroutine panic a panic in any goroutine with no recover there; crashes the whole program created by main.main in goroutine 1
Boundary where one unit of work starts (a request, an order); where recovery belongs handle(o)
Re-panic calling panic(r) again after recovering a value you don't handle if r != nil { panic(r) }
os.Exit ends the program immediately with a code; skips defers os.Exit(3)
*runtime.PanicNilError what panic(nil) panics with (Go 1.21+) panic called with nil argument
When panicking is acceptable bugs, impossible states, broken setup in the source, a program that can't start MustCompile at package level

Summary

  • A panic stops normal execution. The stack unwinds: each function's deferred calls run, last in first out. Unrecovered, it prints the message, a stack trace and exits with status 2.
  • panic(v) panics with any value; the runtime panics for impossible operations: index out of range, nil map write, nil pointer dereference, failed type assertion, integer divide by zero. Each is a bug to fix.
  • recover() only works when called directly by a deferred function; otherwise, or when nothing is panicking, it returns nil.
  • defer + recover + a named result turns a panic into an error, so a bad order or request doesn't take the program down (net/http does this per request). Recovering doesn't fix the bug: log it and fix it.
  • Must functions (regexp.MustCompile) panic on broken setup written in the source.
  • Each goroutine needs its own recover: an unrecovered panic in any goroutine ends the whole program.
  • Panic only for bugs and impossible states; return errors for expected failures, and never let panics escape a library.

Next episode: Packages: the package clause, import paths, exported and unexported names, import aliases, blank and dot imports, init functions and initialisation order, internal packages, and why Go forbids import cycles.