Panic
Use panic for unrecoverable program errors and return errors for expected failures.
A panic stops normal execution in the current goroutine and runs its deferred functions. If no deferred function recovers it, the program exits with a stack trace. Use returned errors for failures callers are expected to handle.
The deferred calls run in last-in, first-out order before the panic is reported.
package main
import "fmt"
func main() {
defer fmt.Println("first defer")
defer fmt.Println("second defer")
fmt.Println("before panic")
panic("unexpected state")
}In production
Reserve panic for conditions that indicate a programming error or broken invariant. Invalid input, missing resources, and network failures are expected outcomes and should normally be returned as errors. An unrecovered panic in any goroutine terminates the process.
Enjoyed this? Get more software craft delivered to your inbox.