Go has a Panic(msg) function. If the panic function is called, execution of the program is stopped. The panic function has a parameter: a message to show.

You can use the panic function if a failure occurs that you don’t want or don’t know how to deal with.

Related course:
Learn How To Code: Google’s Go (golang) Programming Language

Example

Introduction

In the most basic scenario, you call the panic function.
Call the panic function is a simple as this code:

package main

import "fmt"

func main(){
panic("Something went wrong")
fmt.Println("golang")
}

In a terminal, it shows:

$ go run demo.go
panic: Something went wrong

goroutine 1 [running]:
main.main()
    /home/linux/z/demo.go:6 +0x39
    exit status 2

Panic function

Real life scenario: Your program needs to create a file, but you don’t want to deal with error processing.

The panic() function will make the program exit if it cannot create the file.

package main

import "os"

func main(){
_, err := os.Create("/root/example")
if err != nil {
panic("Cannot create file")
}
}
$ go run demo.go
panic: Cannot create file

goroutine 1 [running]:
main.main()
    /home/linux/z/demo.go:8 +0x66
    exit status 2