Junior — Middle
Can you explain what is meant by 'Panic' in the context of programming?
sobes.tech AI
Answer from AI
In Go, the term "panic" denotes a mechanism for handling critical errors, where the program cannot continue normal execution. Calling panic() causes immediate termination of the current goroutine and starts a "panic" process — the call stack unwinds, calling deferred functions (defer). If the panic is not recovered with recover(), the program terminates with an error.
Example usage of panic:
func divide(a, b int) int {
if b == 0 {
panic("division by zero")
}
return a / b
}
func main() {
result := divide(10, 0) // will cause panic
fmt.Println(result)
}
Thus, panic is used for handling unexpected situations when further execution is impossible or dangerous.