Middle+
What is panic in Go and when can it not be recovered?
sobes.tech AI
Answer from AI
In Go, panic is a mechanism used to handle critical errors during program execution. When a panic function is called, the current goroutine's execution is interrupted, and the process of "stack unwinding" begins, during which deferred functions are called.
Panic can be caught using the recover function, which must be called inside a deferred function. If recover is called outside a deferred function, it will not be able to catch the panic.
However, there are situations where a panic cannot be caught:
- If a panic occurs in the main goroutine and is not recovered, the program will terminate abruptly.
- If a panic occurs in system calls or in runtime, which do not provide the recover capability.
- If recover is called outside the context of a deferred function, it will not be able to prevent the program from terminating.
Example:
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Caught a panic:", r)
}
}()
panic("something went wrong")
}
In this example, the panic will be caught and handled, and the program will not terminate abruptly.