What is panic and recover in Go?
Answer
panic stops normal execution and begins unwinding the stack, running deferred functions as it goes. If a panic reaches the top of the goroutine's stack without being recovered, the program crashes with a stack trace. recover() can only be called inside a deferred function — it intercepts the panic and returns the panic value, allowing the program to continue. HTTP servers commonly use this pattern in middleware: defer func() { if r := recover(); r != nil { log.Error(r); w.WriteHeader(500) } }(). Use panic only for truly unrecoverable programmer errors, not for expected runtime errors (use the error return for those).
Previous
What is a goroutine leak and how do you detect it?
Next
What is fmt.Errorf with %w and how do errors.Is / errors.As work?