Select Page

Don’t Panic! Go has you covered

Written By James Perkins

January 27, 2020

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.

You May Also Like…

Are you sorted?

Are you sorted?

Go sort package implements sorting for builtins and user-defined types. It's flexibility makes sorting a breeze!...

Looping in Go

Looping in Go

Looping in Go is fairly similar to any other language that you may of seen in the past, with some slight variations...

Git Command Line Basics

Git Command Line Basics

It's 2020, you have started to lean coding it's great to use an GUI like gitKraken however in some roles you might not...

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *