What is recover in Golang?

Overview

The recover() function in Go Language is used to recover from a goroutine that is in panic, meaning it helps recover from an error that has been raised. The program takes control through recover rather than letting the code crash. recover() is an inbuilt function in Go Language. Below is the prototype of the recover() function:

func recover() interface{}

The following points must be noted about the recover() function:

  1. The recover() function only works if it is called in the goroutine where panic() occurs.
  2. The recover() function only works when called in a deferred function. This is because when a panic occurs, deferred functions do not exit or crash as a normal function would. Hence, recover() should only be called in the deferred function.

Example

Below is an example that demonstrates how to use the recover() function:

package main
import "fmt"
func panicHandler(){
rec := recover()
if rec != nil {
fmt.Println("RECOVER", rec)
}
}
func employee(name *string, age int){
defer panicHandler()
if age > 65{
panic("Age cannot be greater than retirement age")
}
}
func main() {
empName := "Samia"
age := 75
employee(&empName, age)
}

Explanation

As shown in the code above, we call a deferred function, handlePanic, inside the goroutine where panic is expected to occur. This means that when panic occurs and the function employee exits, handlePanic will still run and recover from the panic.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved