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