Senior
What is a panic in Go and how does it differ from an error? How to catch a panic?
sobes.tech AI
Answer from AI
In Go, panic is a mechanism used to handle critical errors, after which the program execution usually terminates. A panic causes the current goroutine to stop immediately and begins the process of stack unwinding, calling deferred functions (defer).
Differences from an error:
- Error (error) — is a regular value returned by a function and can be handled normally.
- Panic (panic) — is an emergency signal about a serious problem, usually not intended for normal handling.
To catch a panic and prevent the program from crashing, the recover() function is used, which can be called inside a deferred function (defer). If recover() is called during stack unwinding, it returns the panic value and stops its propagation.
Example:
func safeCall() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Caught a panic:", r)
}
}()
panic("something went wrong")
}
func main() {
safeCall()
fmt.Println("The program continues")
}