The panic and recover mechanism in Go is used for error handling and debugging in exceptional situations. Here's how you can use it:
Panic: Panic is used to indicate that something unexpected/unrecoverable has occurred and the program cannot continue its normal execution. When a panic occurs, it stops the ordinary flow of a Go program and starts unwinding the stack, executing deferred functions along the way.
You can raise a panic using the panic()
function. For example:
func divide(a, b int) int {
if b == 0 {
panic("Cannot divide by zero")
}
return a / b
}
Recover: Recover is used to regain control over a panicking goroutine. It's generally used to handle and process the panic, allowing the program to avoid termination and continue executing. However, recover can only be used inside a deferred function.
You can recover from a panic using the recover()
function. For example:
func divideWithRecover(a, b int) (result int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
result = -1 // Set some default value if division fails
}
}()
result = a / b // Potential panic if b is zero
return result
}
Here, the deferred function will catch the panic and handle it by recovering. It prints a message and sets a default value instead of allowing the program to terminate.
It is worth noting that recover only works within the same goroutine where the panic occurred and can only recover from the nearest panicking function.
By using panic and recover, you can control how the program handles and recovers from unexpected errors, allowing for better error handling and debugging in Go.