Golang program to recover program after panic condition

Here, we are going to learn how to recover program after panic condition in Golang (Go Language)?
Submitted by Nidhi, on April 02, 2021 [Last updated : March 05, 2023]

Recovering the program after panic condition in Golang

In this program, we will use the recover() function to recover the program from the panic condition.

Golang code to recover the program after panic condition

The source code to recover the program after the panic condition is given below. The given program is compiled and executed successfully.

// Golang program to recover program
// after panic condition

package main

import "fmt"

func Divide(a int, b int) int {
	defer func() {
		fmt.Println(recover())
	}()

	result := a / b
	return result
}
func main() {
	result1 := Divide(5, 0)
	fmt.Println("Result: ", result1)
	result2 := Divide(6, 2)
	fmt.Println("Result: ", result2)
}

Output

runtime error: integer divide by zero
Result:  0
<nil>
Result:  3

Explanation

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

func Divide(a int, b int) int {  
   defer func() {  
      fmt.Println(recover())  
   }()  
   
   result := a / b  
   return result
}  

In the above code, we created a user-defined function Divide() to divide a number by another number and returns the result to the calling function. In this function, we used the recover() function to recover the program from a panic situation. Here "divide by zero"  panic situation may occur and crash the program.

In the main() function, we called the Divide() function with different values and print the result on the console screen.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.