Recovering from Panics
While panics are an essential part of Go's error-handling mechanism, it's crucial to know how to recover from them. Go provides the recover()
function, which allows you to catch and handle panics, preventing your application from crashing.
The recover()
function is typically used within a defer
statement, which ensures that it is called even if the function panics. Here's an example:
package main
import "fmt"
func main() {
result := safeDiv(10, 0)
fmt.Println(result)
}
func safeDiv(a, b int) (result int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
result = 0
}
}()
return a / b
}
In this example, the safeDiv()
function uses a defer
statement to call the anonymous function, which in turn calls recover()
. If the divide()
function panics, the recover()
function will catch the panic and assign a value of 0 to the result
variable, preventing the application from crashing.
When you run this code, the output will be:
Recovered from panic: runtime error: integer divide by zero
0
The recover()
function can also be used to handle specific types of panics. For example, you can check the type of the panic using a type assertion and take appropriate action:
func safeDiv(a, b int) (result int) {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
fmt.Println("Recovered from error:", err)
} else {
fmt.Println("Recovered from unknown panic:", r)
}
result = 0
}
}()
return a / b
}
In this example, the recover()
function checks if the panic value is an error
type and handles it accordingly.
Recovering from panics is an essential skill for Go developers. By understanding how to use recover()
and defer
, you can write more robust and reliable Go applications that can handle unexpected situations gracefully.