Simple Guide to Panic Handling and Recovery in Golang
Golang is now one of the most popular languages for development in the industry. More and more organisations are migrating to use Golang because of its ease of use, concurrency patterns and awesome online community.
Go is extremely simple, and has very limited keywords. It is extremely opinionated, and has readily available patterns to achieve certain tasks. One of them is handling panic and recovering from it gracefully. Let us take a look at it.
First, let us set up our premise. We are writing a function printAllOperations
which will take two integer inputs, and perform sum, subtraction, multiplication and division on them and print out the results.
func printAllOperations(x int, y int) {
sum, subtract, multiply, divide := x+y, x-y, x*y, x/y
fmt.Printf("sum=%v, subtract=%v, multiply=%v, divide=%v \n", sum, subtract, multiply, divide)
}
The main
method will be calling this function, and letting us know that it was able to complete all the operations successfully.
func main() {
x := 20
y := 10
printAllOperations(x, y)
fmt.Println("Exiting main without any issues")
}
On running this code, we will see the following output as expected.
sum=30, subtract=10, multiply=200, divide=2
Exiting…