In Go, panics are exceptional errors that occur during the program execution. The panic function terminates the normal execution flow and starts panicking. However, we can recover from panics using the recover() function. Here's how you can handle and recover from panics in Go:
Panic:
panic()
function when a critical error occurs, and you need to stop the normal execution flow immediately.panic("Something went wrong!")
can be used to panic the program and terminate execution.Recover:
recover()
function inside a deferred function.Here's an example illustrating the usage of panic and recover in Go:
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Recovered from panic:", err)
}
}()
fmt.Println("Before panic")
panicker()
fmt.Println("After panic")
}
func panicker() {
fmt.Println("Inside panicker")
panic("Manually panicked!")
fmt.Println("After panic in panicker") // This line is not executed
}
In the above example, the panicker()
function intentionally causes a panic. However, the deferred function inside the main()
function recovers from the panic using the recover()
function. The program execution continues after the panicker() call, and the message "Recovered from panic: Manually panicked!" is printed.
Remember, it's generally recommended to use panics and recovers sparingly and only for exceptional errors that cannot be handled in regular control flow.