Recover in Golang


In Golang, the recovery mechanism provides a way to deal with panic and recover from it. Panic is an unexpected error that can cause the program to terminate. In this article, we are going to discuss what is recovered in golang. Here we are going to use two different methods: using handlePanic as well as the main() function along with examples to elaborate the concept.

Syntax

recover()

In this Syntax, The handlePanic function is used in Go to recover from panics. It checks if a panic occurred using the recover() function, which returns the value passed to panic(). If there was a panic, the code inside the if statement is executed to handle the panic situation.

defer handlePanic()

In this code Syntax, the handlePanic function is deferred using the defer keyword within the main() function. The defer statement ensures that the handlePanic function will be called automatically just before the main() function returns, regardless of whether an error or panic occurred during the execution of the rest of the program logic.

panic()

This is a golanguages built in function that is used to immediately stop the program. the string used in argument is seen as a message for the reason to panic.

Algorithm

  • Place the code that may potentially panic inside a deferred function.

  • Use the recover() function inside a deferred function to catch and handle panics.

  • Check the value returned by recover(). If it returns a non-nil value, it indicates that a panic occurred.

  • Handle the panic situation by taking appropriate actions, such as logging an error message or gracefully recovering from the panic.

  • Use the defer keyword to ensure that the deferred function is called even if a panic occurs.

  • Optionally, you can re-panic the error if necessary or perform additional recovery operations.

  • Continue executing the remaining code after the recovery block to ensure the program's flow is not interrupted by the panic.

Example 1

In this code, the handlePanic function is defined to handle any panic that occurs within the program. It checks if a panic has been recovered and if so, prints a message indicating the recovery. The main function defers the execution of handlePanic, ensuring that it is called if a panic occurs anywhere within the main function or its child functions. In this example, a panic is deliberately triggered using the panic function to simulate an unexpected error.

package main

import (
   "fmt"
)

func handlePanic() {
   if r := recover(); r != nil {
      fmt.Println("Recovered from panic:", r)
   }
}

func main() {
   defer handlePanic()

   panic("Something went wrong!")

   fmt.Println("This line will not be executed.")
}

Output

Recovered from panic: Something went wrong!

Example 2

In this example, the handlePanic function is defined to handle any panic that occurs within the program. It checks if a panic has been recovered and if so, prints a message indicating the recovery. The main function defers the execution of handlePanic, ensuring that it is called if a panic occurs anywhere within the main function or its child functions. In this example, the main function executes some logic and then deliberately triggers a panic using the panic function. However, since the panic is handled by handlePanic, the program continues to execute, and the line after the panic is not executed. 

package main

import (
   "fmt"
)

func handlePanic() {
   if r := recover(); r != nil {
      fmt.Println("Recovered from panic:", r)
   }
}

func main() {
   defer handlePanic()

   fmt.Println("Executing the main function.")

   panic("Something went wrong!")

   // This line will not be executed.
   fmt.Println("This line will not be executed.")
}

Output

Executing the main function.
Recovered from panic: Something went wrong!

Conclusion

The recovery methods in Golang provide a way to deal with panics, allowing programs to handle unexpected problems gracefully and successfully. By combining recovery with latency, we can catch a panic and take the necessary action to resolve the error, clean up resources, or keep the project running. Careful error handling and protection must be implemented to prevent panic attacks and ensure the security and reliability of Golang applications.

Updated on: 20-Jul-2023

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements