Sobes.tech
Middle — Middle+

Selgitage süsteemi taastamise mehhanismi pärast tõrke Recover kasutamise kontekstis.

sobes.tech AI

Vastus AI-lt

In Go, the recover mechanism is used to catch panic and restore the normal execution of the program. This allows the system, after an error, not to terminate abruptly, but to handle the error and continue working.

Main idea:

  • When a panic occurs, the execution of functions is interrupted and the "stack unwinding" begins.
  • If in one of the called functions there is a deferred (defer) call that invokes recover(), it catches the panic and returns the error value.
  • After that, the program can handle the error and continue execution.

Example:

func safeDivide(a, b int) int {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovery after panic:", r)
        }
    }()
    return a / b // if b == 0, panic occurs
}

func main() {
    fmt.Println(safeDivide(10, 2)) // 5
    fmt.Println(safeDivide(10, 0)) // Recovery after panic: runtime error: integer divide by zero
}

This way, recover helps make the system resilient to unexpected errors and prevents abrupt termination.