Sobes.tech
Junior — Middle

Explain the interaction mechanism of panic, defer, and recover functions in the Go programming language.

sobes.tech AI

Answer from AI

In Go, the functions panic, defer, and recover are related to error handling and exceptional situations.

  • panic causes an immediate termination of the current function and starts a "panic" process, which propagates up the call stack, invoking deferred functions defer.
  • defer postpones the execution of a function until the current function exits, allowing cleanup or handling after a panic.
  • recover allows catching a panic within a deferred function and prevents the program from crashing.

Example:

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

    fmt.Println("Before panic")
    panic("something went wrong")
    fmt.Println("This will not run")
}

Here, panic triggers an error, defer with recover catches it, and the program continues to run without crashing.