Junior — Middle
What are the differences between panic and a critical error that stops program execution?
sobes.tech AI
Answer from AI
In Go, a panic is a mechanism that occurs during program execution when a critical error happens, such as out-of-bounds slice access or an explicit call to panic(). A panic causes the current goroutine to terminate immediately and begins the process of "stack unwinding," calling deferred functions (defer). If the panic is not recovered using recover(), the program will terminate with an error.
A critical error that stops program execution can be caused by a panic, but it can also be related to fatal system-level errors (e.g., segmentation fault) that cannot be handled in code.
Main differences:
- Panic — a controlled mechanism that can be intercepted and handled with
recover(). - Critical error — may be unhandled, leading to immediate program termination without recovery.
Example of using panic and recover:
func mayPanic() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("something went wrong")
}
func main() {
mayPanic()
fmt.Println("Program continues")
}