Golang: Technique for Handling Panic — Simply explained

Panic vs Error in Golang

Photo by Sigmund on Unsplash
valueReturned, err = doSomethingValuable() //function which returns 
//a value and error
if err != nil {
fmt.Printf("Err encuntered %w", err)
}

Inducing a Panic

package handlepanicimport "errors"func AddingLargeNumbers() {        var largeNumber int8
largeNumber = 127
largeNumber += 1 if largeNumber < 0 {
panic(errors.New("number is too large and has
wrapped."))//1
}
print(largeNumber)
}
panic([]interface)

Recovering from panic

Photo by William Farlow on Unsplash
package mainimport (
"fmt"
"handlepanic"
)
func main() {
defer func() {
if err := recover(); err != nil { //1
fmt.Println("Gentle Recovery from panic err:
%w", err)
}
cleanUp() //2
}()
fmt.Println("Launching function...")
handlepanic.AddingLargeNumbers() //3
}
func cleanUp() { fmt.Println("Continue and do cleanup")
}
$ go run main.go
Launching function...
Gentle Recovery from panic err: %w number is too large and has wrapped.
Continue and do cleanup
$ go run main.go
Launching function...
panic: number is too large and has wrapped.
goroutine 1 [running]:
handlepanic.AddingLargeNumbers(...)
C:/Users/yaoji/Documents/Courses/Self Learning/Go/handlingPanic/handlePanic.go:13
main.main()
C:/Users/yaoji/Documents/Courses/Self Learning/Go/handlingPanic/example/main.go:17 +0x89
exit status 2
Photo by Andrey Metelev on Unsplash

--

--

--

Writing to soothe the soul, programming to achieve flow

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Developer Circle Community Challenge: Pilgrimage with Nchito

Plug is now Available on the Chrome Extension Store & Firefox Add-on Store 🚀🚀

How to use different Environment Variables in Angular 13

Angular 13 Environment Variable configuration

How to Create and Configure Sudo User on Arch Linux

Switch-User-Arch-Linux

#EDA Enough already with ‘Event Streaming’ **

Downgrade PHP8.1 to PHP8.0 or PHP7.4 on Ubuntu 22.04

Camera Error Code 0xa00f4244 Facing in Windows 10, let settle it in this our post.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mipsmonsta

Mipsmonsta

Writing to soothe the soul, programming to achieve flow

More from Medium

How to Lighten Colors Programmatically

Golang automatic code formatting : Code like a Pro

Plugging logrus into go-retryablehttp

How To Install And Setup Go Language On Ubuntu (Complete Guide)

How To Install And Setup Go Language On Ubuntu (Complete Guide)