Golang panic recover example
This is a Panic and Recover example that handles an error that occurs during the execution of a program. We have used the recover function to prevent the termination of the program and recovers the program from panic.
In this example, r := recover() is used to detect any occurrence of panic in the program and assign the panic message to r.
Example
package main
import (
"errors"
"fmt"
)
var result = 1
func chain(n int) {
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
}
}()
if n == 0 {
panic(errors.New("Cannot multiply a number by zero"))
} else {
result *= n
fmt.Println("Output: ", result)
}
}
func main() {
chain(5)
chain(2)
chain(0)
chain(8)
}
Output: 5
Output: 10
Cannot multiply a number by zero
Output: 80
Most Helpful This Week
How do you set headers in an HTTP request with an HTTP client in Go?
How to initialize the slice with values using a slice literal?
How do you handle HTTP client caching in Go?
How do you handle HTTP server health checks in Go?
How do you send an HTTP POST request with an HTTP client in Go?
Go program to find Name Server (NS) record of a domain