Skip to content

Go Goroutine Panic

DodaTech 1 min read

In this tutorial, you'll learn about Go Goroutine: Panic Recovery. We cover key concepts, practical examples, and best practices.

Goroutine panic handling -- Recover from panics inside goroutines to prevent them from crashing the entire program.

The Problem

Panics in goroutines are not caught by deferred recover in the parent goroutine. Each goroutine must have its own recover() call.

Wrong

go func() {
    panic("unexpected error") // Crashes the whole program!
}()

Output:

// panic: unexpected error
// Program crashes
go func() {
    defer func() {
        if r := recover(); r != nil {
            log.Printf("Recovered from panic: %v", r)
        }
    }()
    panic("unexpected error") // Recovered!
}()
time.Sleep(time.Millisecond)

Output:

2026/06/24 Recovered from panic: unexpected error
// Program continues running

Prevention

  • Always add defer/recover in goroutines that may panic
  • Log the panic for debugging
  • Recover does not fix data corruption -- design safely
  • Use errgroup for structured error handling
  • Panic recovery in HTTP handlers is automatic (Recovery middleware)

Common Mistakes with goroutine panic

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Can parent goroutine recover child panic?**

No. Each goroutine must recover its own panics.

What if recover() is not in a deferred function?

It won't work. recover() only works inside defer.

Should I recover all panics?

Recover gracefully, but re-panic if state is unrecoverable.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro