Basic Error Handling with ‘panic’ and ‘recover’ in Golang
--
Error handling is an essential aspect of writing robust programs. Go (Golang) provides built-in mechanisms for error handling, among which ‘panic’ and ‘recover’ are the most unique. This article explores the basic principles of using ‘panic’ and ‘recover’ for error handling in Golang.
1. The ‘panic’ Function
In Go, the ‘panic’ function is used to immediately stop the execution of a function and propagate an error up the call stack.
1.1 Basic Usage
Here’s how to use ‘panic’:
func divide(a, b int) int {
if b == 0 {
panic("Division by zero")
}
return a / b
}
In this example, the function panics if someone tries to divide a number by zero.
1.2 Propagation
When ‘panic’ is called, the execution of the current function stops, and the function that called it also stops, propagating the panic up the call stack. This continues until it reaches ‘main()’, after which the program terminates.
2. The ‘recover’ Function
The ‘recover’ function is used to regain control over a panicking goroutine. ‘recover’ can only be used inside a deferred function and helps you to stop the panic from propagating.
2.1 Basic Usage
Here’s a basic example:
func safeDivision(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Caught a panic: %v", r)
}
}()
if b == 0 {
panic("Division by zero")
}
result = a / b
return
}
In this example, the deferred function captures the panic, and the ‘recover’ function stops the panic from propagating further.
2.2 Proper Usage
Although ‘panic’ and ‘recover’ are available, they are often discouraged for regular error handling in favor of explicit error return values. They are mostly used for exceptional cases that should halt normal execution.