Junior — Middle
How is the handling of panic states and error processing caused by emergencies implemented in Go?
sobes.tech AI
Answer from AI
In Go, panic states are used to handle critical errors that usually lead to an abrupt termination of the program. The mechanism of deferred calls (defer) along with the recover function is used to manage such situations, allowing to catch a panic and prevent the program from crashing.
Example:
package main
import "fmt"
func safeDivision(a, b int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovery after panic:", r)
}
}()
if b == 0 {
panic("division by zero")
}
fmt.Println("Result:", a/b)
}
func main() {
safeDivision(10, 2) // Will output: Result: 5
safeDivision(10, 0) // Recovery after panic: division by zero
}
Thus, panic is used to signal serious errors, and recover is used to handle them and prevent an abrupt program termination.