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

Before we handle panic “attacks”, let’s learn to induce 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

--

--

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