Middle — Middle+
How should the Recovery mechanism be properly declared in a system?
sobes.tech AI
Answer from AI
In Go, the recover mechanism is used to catch panics (panic) and prevent the program from crashing. Proper declaration and use of recover should occur inside a function deferred with defer. This allows catching a panic if it occurred in the called function and handling it.
Example of correct usage:
func safeCall() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
// Code that might cause a panic
panic("something went wrong")
}
Key points:
recoveronly works inside a deferred function (defer).- If
recoveris called outsidedefer, it will not catch a panic. - Usually,
recoveris used for error logging and ensuring program stability.