Go Goroutine Panic
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
Right
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
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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
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