Recover in Go

Go: Recover

What is Recover?

In Go, the recover function is used to handle panics by catching and recovering from them. When a panic occurs, the Go runtime searches for a deferred recover call in the current goroutine and executes it if found. The recover function returns the value passed to the panic call that triggered the panic, allowing you to inspect and potentially recover from the panic.

How recover works in Go

Here's an example to demonstrate how recover works in Go:

    func main() {
        defer func() {
            if r := recover(); r != nil {
                fmt.Println("Recovered:", r)
            }
        }()
        panic("Oops! Something went wrong...")
    }

Explaination: we've defined an anonymous function that will be deferred until the end of the main function. Inside this function, we call the recover function and check if it returns a non-nil value. If it does, we print a message indicating that we've recovered from a panic and print the value that was passed to the panic function.

We then deliberately trigger a panic by calling panic with a string message. This will cause the program to exit unless we recover from the panic using the recover function.

When we run this program, we'll see the following output:


Recovered: Oops! Something went wrong...

  • The recover function successfully catches the panic and allows us to handle it gracefully by printing a message instead of abruptly terminating the program.
  • It's important to note that the recover function only works within a deferred function. If you call it outside of a deferred function, it will simply return nil. Additionally, calling recover multiple times within the same deferred function will only catch the first panic that occurred.

Previous Article