Junior — Middle
Mis on vajadus kasutada recover funktsiooni defer sees Go-s?
sobes.tech AI
Vastus AI-lt
In Go, the recover function is used to catch panic and prevent the program from crashing unexpectedly. However, recover only works if it is called inside a deferred function (defer).
Using recover inside defer allows:
- Safely handling a panic, for example, logging the error or cleaning up resources.
- Continuing program execution after a panic, if possible.
Example:
func safeFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
// Code that may cause panic
panic("something went wrong")
}
If recover is called outside of defer, it will not catch the panic, and the program will terminate unexpectedly. Therefore, recover should always be placed inside defer for proper exception handling.