Sobes.tech
Junior — Middle

What is the necessity of using the recover function inside defer in Go?

sobes.tech AI

Answer from AI

In Go, the recover function is used to catch a panic (panic) and prevent the program from crashing. However, recover only works if called inside a deferred function (defer).

Using recover inside defer allows:

  • Safely handling a panic, for example, logging the error or cleaning up resources.
  • Continuing program execution after a panic, if possible.

Example:

func safeFunction() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    // Code that might cause a panic
    panic("something went wrong")
}

If recover is called outside defer, it will not catch the panic, and the program will crash. Therefore, recover is always placed inside defer for proper exception handling.

What is the necessity of using the recover function… - sobes.tech