Step Over to Go Part 10 of 50
  1. 1 Goodbye .csproj, Hello go.mod
  2. 2 The Phrasebook: C# Concepts in Go Terms
  3. 3 You Know .NET, Now Meet the Go Toolchain
  4. 4 No Enums? No Problem (Sort Of)
  5. 5 Generics: Late to the Party
  6. 6 The Million Dollar Mistake, Differently
  7. 7 Your Class Is Now a Struct (And That's Fine)
  8. 8 Where Did My Properties Go?
  9. 9 if err != nil: Your New Reality
  10. 10 Panic and Recover: The Emergency Exit
  11. 11 The switch Statement You Always Wanted
  12. 12 Stack vs Heap: Go's Escape Analysis
  13. 13 Pointers Without the Pain
  14. 14 Slices Are Not Arrays (And Neither Is List<T>)
  15. 15 Channels: The sync You Didn't Know You Wanted
  16. 16 Context Is King
  17. 17 Async/Await vs Goroutines: A Mindset Shift
  18. 18 select: Multiplexing Like a Pro
  19. 19 Mutexes and WaitGroups: When Channels Aren't the Answer
  20. 20 The Empty Interface and Type Assertions
  21. 21 Composition Over Inheritance (For Real This Time)
  22. 22 Implicit Interfaces: Scary Then Brilliant
  23. 23 Benchmarks and Profiling Out of the Box
  24. 24 Mocking in a Language Without Mockito
  25. 25 Multi-Module Repos: Monorepo Thinking
  26. 26 Organising a Real Project
  27. 27 Testing Without a Framework
  28. 28 Configuration Without IOptions<T>
  29. 29 Database Access: database/sql vs Entity Framework
  30. 30 Debugging: Delve vs Visual Studio's Comfort
  31. 31 Generate All the Things
  32. 32 GORM and Friends: When You Do Want an ORM
  33. 33 HTTP Services: net/http vs ASP.NET Core
  34. 34 JSON: Struct Tags and the Marshal Dance
  35. 35 Linting and Formatting: gofmt Is Non-Negotiable
  36. 36 Logging: slog and the Structured Logging Story
  37. 37 Shrinking Binaries and Build Tags
  38. 38 Dockerfile for Go: Simpler Than You'd Think
  39. 39 GitHub Actions for Go Projects
  40. 40 Health Checks and Readiness Probes
  41. 41 Kubernetes and Go: A Natural Fit
  42. 42 AWS Lambda and Go: Cold Starts That Don't Hurt
  43. 43 Metrics, Traces, and Logs: The OpenTelemetry Way
  44. 44 Single Binary Deploys: The Killer Feature
  45. 45 Versioning Your Modules
  46. 46 What I Actually Miss From C#
  47. 47 What I'll Never Go Back For
  48. 48 Six Months In: Was It Worth It?
  49. 49 Forty-Eight Posts on Moving From C# to Go, in the Right Order
  50. 50 Range-Over-Func Iterators for People Who Miss LINQ
About this series

Panic and Recover: The Emergency Exit

So Go doesn't have exceptions. Except… it kind of does. They're called panic and recover, and they work almost exactly like throw and catch.

If you use them like exceptions, other Go developers will judge you. Harshly. Let's understand why they exist, when to use them, and why the judgment is (mostly) deserved.

What Panic Does

panic stops normal execution and begins unwinding the stack:

func divide(a, b int) int {
    if b == 0 {
        panic("division by zero")
    }
    return a / b
}

func main() {
    result := divide(10, 0)  // panics here
    fmt.Println(result)      // never reached
}

Output:

panic: division by zero

goroutine 1 [running]:
main.divide(...)
        /app/main.go:7
main.main()
        /app/main.go:12
exit status 2

Sound familiar? It's an unhandled exception with a stack trace.

Deferred functions still run during a panic:

func riskyOperation() {
    defer fmt.Println("cleanup runs")  // this executes
    panic("oh no")
    fmt.Println("never reached")
}

What Recover Does

recover catches a panic. It only works inside a deferred function:

func safeOperation() (err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered from panic: %v", r)
        }
    }()
    
    riskyOperation()  // might panic
    return nil
}

If riskyOperation panics, recover() catches it and we convert it to an error. The function returns normally instead of crashing.

This is literally try/catch:

// C# equivalent
try
{
    RiskyOperation();
}
catch (Exception ex)
{
    return new Error($"recovered from exception: {ex.Message}");
}

Why Go Developers Judge You

So if panic/recover is just exceptions by another name, why not use them that way?

Because Go's error philosophy is that errors are expected, panics are not.

  • Errors are things that can reasonably happen: file not found, network timeout, invalid input
  • Panics are things that shouldn't happen: nil pointer dereference, index out of bounds, programmer bugs

When you use panic for normal errors, you're saying “this should never happen” when what you mean is “I didn't want to write if err != nil.”

The community has strong opinions about this:

// This will get you judged
func ParseConfig(path string) Config {
    data, err := os.ReadFile(path)
    if err != nil {
        panic(err)  // NO - missing file is a normal error
    }
    // ...
}

// This is fine
func MustParseConfig(path string) Config {
    // "Must" in the name signals this panics
    // Only use at startup where failure = can't run
}

When Panic Is Appropriate

Despite the judgment, there are legitimate uses:

1. Truly Unrecoverable Programmer Errors

func processItem(item *Item) {
    if item == nil {
        panic("processItem called with nil item")
    }
    // This is a programming error - the caller screwed up
    // Not a runtime condition we should handle gracefully
}

2. Initialisation Failures

var db = mustConnect()

func mustConnect() *sql.DB {
    db, err := sql.Open("postgres", os.Getenv("DATABASE_URL"))
    if err != nil {
        panic(fmt.Sprintf("database connection failed: %v", err))
    }
    return db
}

If the program can't start without a database, panicking at init is reasonable. There's nothing useful to do with the error.

3. The “Must” Convention

Standard library examples:

// template.Must panics if parsing fails
var templates = template.Must(template.ParseGlob("*.html"))

// regexp.MustCompile panics if pattern is invalid
var emailRegex = regexp.MustCompile(`^[a-z]+@[a-z]+\.[a-z]+$`)

The Must prefix tells callers “this panics on error, only use with compile-time constant inputs.”

4. Deep Recursion Bailout

Sometimes you're deep in recursion and unwinding through error returns is painful:

func parse(tokens []Token) (result AST, err error) {
    defer func() {
        if r := recover(); r != nil {
            if parseErr, ok := r.(parseError); ok {
                err = parseErr
            } else {
                panic(r)  // re-panic if it's not our error
            }
        }
    }()
    
    return parseExpression(tokens), nil
}

func parseExpression(tokens []Token) AST {
    // Deep recursive descent
    // ...
    if somethingWrong {
        panic(parseError{msg: "unexpected token", pos: pos})
    }
}

This is controversial but accepted in parsers and similar deep-recursion scenarios. Note that the panic is recovered at the boundary and converted to an error.

The Boundary Pattern

The key pattern: never let panics escape your package.

If your code might panic (or call code that might panic), recover at the boundary:

// Public API - never panics
func (s *Service) ProcessRequest(req Request) (Response, error) {
    defer func() {
        if r := recover(); r != nil {
            // Log, maybe alert
            log.Printf("panic in ProcessRequest: %v", r)
        }
    }()
    
    return s.doProcess(req)  // internal, might panic
}

HTTP handlers often do this:

func recoveryMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if err := recover(); err != nil {
                log.Printf("panic: %v\n%s", err, debug.Stack())
                http.Error(w, "Internal Server Error", 500)
            }
        }()
        next.ServeHTTP(w, r)
    })
}

A panic in a handler becomes a 500 response, not a crashed server.

Panic Values

Unlike C# where you throw Exception objects, you can panic with any value:

panic("a string")
panic(42)
panic(errors.New("an error"))
panic(MyCustomType{})

When recovering, you get an interface{}:

if r := recover(); r != nil {
    switch v := r.(type) {
    case error:
        log.Printf("error: %v", v)
    case string:
        log.Printf("string: %s", v)
    default:
        log.Printf("unknown: %v", v)
    }
}

Best practice: panic with error values or strings. Makes recovery predictable.

Comparison with C#

Aspect C# Exceptions Go Panic/Recover
Normal errors Often used Strongly discouraged
Programmer bugs Appropriate Appropriate
Syntax try/catch/finally defer/recover
Stack traces Automatic Available via debug.Stack()
Filtering Catch by type Check recovered value
Re-throwing throw; panic(r)
Custom types Exception subclasses Any type (usually error)
Cultural norm Expected Emergency only

The Test Exception

One place where panic is universally accepted: tests.

func TestSomething(t *testing.T) {
    result := process(input)
    
    if result != expected {
        t.Fatalf("got %v, want %v", result, expected)  // this panics
    }
}

t.Fatal and t.Fatalf panic to abort the test. This is fine. Tests are the one place where “stop everything” is the right response to failure.

The Honest Take

When I use panic:

  • Must functions for startup initialisation
  • Genuinely impossible conditions (defensive programming)
  • Test assertions via t.Fatal

When I don't use panic:

  • File not found
  • Network errors
  • Invalid user input
  • Anything that can reasonably happen at runtime

The rule I follow: If I'm tempted to panic, I ask: “Is this a bug in my program, or is this something that could happen in production?” Bugs can panic. Production conditions should return errors.

What About Performance?

One argument for panic: “it's faster because you don't have to check errors at every level.”

This is technically true but practically irrelevant. Error checking is a comparison and conditional jump. The performance difference is unmeasurable in real code.

Don't let performance justify panic. If you're that performance-sensitive, you're probably not writing Go anyway.


Coming up: Go's switch statement. More powerful than C#'s, with type switching, expression cases, and some surprises around fallthrough.