Junior — Middle
Can you explain the concept of failure recovery in the Go language?
sobes.tech AI
Answer from AI
In Go, the concept of recovery after a failure is implemented using the panic and recover mechanisms.
panicis used to generate an error that interrupts the normal flow of the program.recoverallows catching a panic and continuing execution if called inside a deferred function (defer).
This is useful for handling unexpected errors and preventing the program from crashing.
Example:
package main
import "fmt"
func riskyFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("something went wrong")
fmt.Println("This code will not execute")
}
func main() {
riskyFunction()
fmt.Println("Program continues")
}
In this example, panic causes an error, but thanks to recover, the program does not crash and continues to run.