In Go, errors are typically handled using a combination of defer
statements and the panic
and recover
functions. Here's how you can use error handling with defer
statements:
func divide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic occurred: %v", r)
}
}()
if b == 0 {
panic("division by zero")
}
result = a / b
return result, nil
}
Within the function, use defer
to define a function that checks for a panic using the recover
function. If a panic occurs, it sets the err
variable with an appropriate error message.
Use the panic
statement to raise an error condition (panic) if needed. In the example above, a panic is raised if the divisor b
is zero.
When calling the function, check the returned error value and handle it accordingly. For example:
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
In the example above, if the divisor is zero, a panic occurs and the error is caught by the deferred function. The error message is then returned.
Note: The panic
and recover
mechanism in Go is typically used in exceptional situations when the program cannot continue executing normally. It is not intended for regular error handling. Instead, it's recommended to use the error
type for typical error conditions and return them explicitly.