Recover
// Importing necessary package.
import "fmt"
// mayPanic function deliberately panics with a custom error message.
func mayPanic() {
panic("a problem")
}
// The main function, where the execution of the program begins.
func main() {
// Using a deferred anonymous function to recover from panics.
defer func() {
// The recover function is used to catch a panic.
if r := recover(); r != nil {
// Handling the panic by printing the recovered error message.
fmt.Println("Recovered. Error:\n", r)
}
}()
// Calling the mayPanic function, which panics intentionally.
mayPanic()
// This line will be reached only if there is no panic in the mayPanic function.
fmt.Println("After mayPanic()")
}output
Last updated