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
Golang program for implementation of Merge Sort
Go program to reading plain text files
How To Make HTTP Requests in Go?
GO Program to Generate Fibonacci Sequence Up to a Certain Number
How to create Slice using Make function in Golang?
Invalid memory address or nil pointer dereference error in Golang
What is the default HTTP server in Go?
Various examples of printing and formatting in Golang
Golang Program to Triangle of Alphabets
Naming Conventions for Golang Functions