🐹 Go (Golang) Intermediate

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).