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

Problem Solution:

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

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.






Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.