Overview
Apanic typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.
When to Use Panic
Panic should be reserved for exceptional situations:- Unrecoverable errors during initialization
- Programming errors that indicate bugs
- Situations where continuing would be dangerous
- Errors that “should never happen”
Basic Panic Usage
The simplest use of panic is with a string message:Panic on Unexpected Errors
A common use of panic is to abort if a function returns an error value that we don’t know how to (or want to) handle:Complete Example
Output
Running this program will cause it to panic, print an error message and goroutine traces, and exit with a non-zero status:When the first panic in
main fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment the first panic out.What Happens During a Panic
When a function panics:- Execution stops - The function stops executing immediately
- Deferred functions run - Any deferred functions are executed in reverse order
- Stack unwinds - The panic bubbles up the call stack
- Program terminates - Unless recovered, the program crashes with a stack trace
Panic vs Errors
Use Errors for
- Expected failure conditions
- Recoverable problems
- Validation failures
- Network/IO issues
- User input errors
Use Panic for
- Programming bugs
- Impossible situations
- Initialization failures
- Critical system errors
- Unrecoverable states
Best Practices
Don't use panic for normal error handling
Don't use panic for normal error handling
Go’s philosophy is to use explicit error return values for all expected error conditions. Reserve panic for truly exceptional situations.
Use panic in library initialization
Use panic in library initialization
It’s acceptable to panic during
init() or package initialization if the library cannot function without certain preconditions.Panic for programmer errors
Panic for programmer errors
Use panic to catch bugs during development, such as invalid function arguments that should never happen in correct code.
Related Topics
Defer
Learn how deferred functions interact with panic.
Recover
Discover how to recover from panics gracefully.