Junior — Middle
What methods can be used to intercept and handle panic-type errors in a program?
sobes.tech AI
Answer from AI
In Go, the mechanism recover used together with defer is employed to catch and handle panic errors. The recover function allows catching a panic and preventing the program from crashing.
Example:
func safeFunction() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Panic caught:", r)
}
}()
// Code that might cause panic
panic("something went wrong")
}
func main() {
safeFunction()
fmt.Println("The program continues to run")
}
In this example, defer postpones the execution of an anonymous function that calls recover. If a panic occurs in safeFunction, it will be caught and handled, allowing the program to continue running.