Overview
Go makes it possible to recover from a panic by using therecover built-in function. A recover can stop a panic from aborting the program and let it continue with execution instead.
Why Use Recover
An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.In fact, this is what Go’s
net/http package does by default for HTTP servers - it recovers from panics in handlers to keep the server running.Basic Recover Usage
recover must be called within a deferred function. When the enclosing function panics, the defer will activate and a recover call within it will catch the panic:
Complete Example
Output
How Recover Works
Therecover function:
- Returns nil in normal execution - When there’s no panic, recover returns nil
- Returns panic value during panic - When called during a panic, it returns the value passed to panic
- Stops panic propagation - Calling recover stops the panic from unwinding the stack further
- Must be in deferred function - Only works when called directly inside a defer
Practical Example: Safe Goroutine Execution
Web Server Example
When to Use Recover
In long-running servers
In long-running servers
Recover from panics in individual request handlers or goroutines to keep the server running, rather than letting one error crash the entire service.
At package boundaries
At package boundaries
Use recover at the top level of exported functions in libraries to prevent internal panics from crashing the caller’s program unexpectedly.
In plugin systems
In plugin systems
When executing third-party or user-provided code, recover can protect your application from panics in that code.
Not for normal error handling
Not for normal error handling
Don’t use panic/recover as a substitute for normal error handling with error return values. Use it only for truly exceptional situations.
Recover Patterns
Pattern 1: Logging and Re-panicking
Pattern 2: Converting Panic to Error
Pattern 3: Cleanup Before Propagating
Best Practices
Use in deferred functions only
recover only works when called directly inside a deferred function.
Check for nil
Always check if recover() returns nil before assuming a panic occurred.
Log panic information
Log the panic value and stack trace for debugging when recovering.
Don't overuse
Use recover sparingly - prefer normal error handling for expected failures.
Common Mistakes
Getting Stack Traces
When recovering from a panic, it’s useful to capture the stack trace:Testing Functions That Panic
In tests, you can verify that a function panics as expected:Panic, Defer, and Recover Together
These three mechanisms work together to provide robust error handling:Related Topics
Panic
Learn when and how to use panic in Go.
Defer
Understand how defer enables recover to work.
Errors
Master Go’s standard error handling approach.