Junior — Middle
Explain the concept of the evacuation mechanism in the Go language and its purpose
sobes.tech AI
Answer from AI
In the Go language, the evacuation mechanism (panic and recover) is used to handle unexpected errors and exceptional situations during program execution.
panicis a call that interrupts the normal execution of the program, triggering a chain of deferred functions (defer) and ultimately terminating the program ifpanicis not recovered.recoveris a function that can be called within a deferred function (defer) to catch a panic and prevent the program from terminating.
Purpose of the mechanism:
- Allows handling critical errors that are impossible or inconvenient to handle with regular methods.
- Provides the ability to recover from an error and continue program execution.
Example:
func safeDivide(a, b int) int {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovery after panic:", r)
}
}()
if b == 0 {
panic("division by zero")
}
return a / b
}
Here, when attempting to divide by zero, panic is called, but thanks to recover, the program does not crash unexpectedly, and the error is handled.