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.
paniccauses an immediate termination of the current function and starts a "panic" process, which propagates up the call stack, invoking deferred functionsdefer.deferpostpones the execution of a function until the current function exits, allowing cleanup or handling after apanic.recoverallows 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.