Q:

Golang program to recover program after panic condition

belongs to collection: Golang Miscellaneous Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang program to print the current user id... >>
<< Golang program to terminate the program with a spe...