Don't Panic! Go has you covered


In this short blog post we are going to cover Panic in Go. Go has a fantastic functionality that lets you panic if you get an unexpected error and want you application to stop the execution.

A common use of panic is to abort if a function returns an error that we don’t know how to handle. Here’s an example of panic if we get an unexpected error when creating a new file.

package main import "os" func main() { panic("an unexpected error has happened! I am Panicking") _, err := os.Create("/testing/file") if err != nil { panic(err) } }

If you were to run this you would get a the following printed to your console panic: an unexpected error has happened! I am Panicking and any goroutine traces are printed, and the application will exit with a non-zero status in this case a 2 status, you can try for yourself by using this link to the go playground.