How to handle panics and recover from them in Go using recover()?

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:

  1. Panic:

    • Use the panic() function when a critical error occurs, and you need to stop the normal execution flow immediately.
    • For example, panic("Something went wrong!") can be used to panic the program and terminate execution.
  2. Recover:

    • To recover from a panic, you need to use the recover() function inside a deferred function.
    • Use the defer keyword before the function that might panic or at the beginning of the main function to ensure recovery is attempted at any panic.
    • The recover() function is only effective if called from a deferred function.
    • The recover() function returns the value passed to the panic() function. If there was no panic, it returns nil.
    • You can use type assertions to check the type of the recovered value and handle it accordingly.

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.