Middle
What is the recover function in Go?
sobes.tech AI
Answer from AI
The recover function in Go is used to catch a panic.
recover()returns nil if no panic occurs or if it was not called inside a deferred function.- If a
panicis invoked, andrecover()is called inside a deferred function,recover()intercepts the value passed topanicand stops the propagation of the panic. - Without
recover, a panic interrupts the normal execution of the program.
Example of usage:
package main
import "fmt"
func main() {
defer func() { // Deferred function where recover is used
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
fmt.Println("Program starts")
panic("Something went wrong!") // Trigger a panic
fmt.Println("This code will not be executed")
}