golang

The Golang Panic Method

In the Go programming language, panic is a mechanism that indicates an unexpected error happened in your program. In most cases, we use the panic mechanism to fail if an error shouldn’t occur. A panic can be raised by the program or manually by a programmer.

This article will teach how to implement panic in the Go programming language using the panic() method.

The Golang Panic Method

We use the panic() method to raise a panic in Go programming. This built-in method returns a panic message and terminates the program.

Note: the panic waits for ongoing goroutines to complete and return. Once all pending tasks are completed, the panic method will end the program.

The syntax for the panic function is as shown:

func panic(v interface{})

We can pass an error message to print once the panic is encountered. When the panic method is executed, it kills the program and returns the specified method and the stack trace up to where the panic was encountered.

The following example programs panics automatically due to an illegal operation

package main
import "fmt"
func main() {
    var arr [3]int
    arr[0] = 1
    arr[1] = 2
    arr[2] = 3
    // out of bound index access
    fmt.Println(arr[5])
}

In the previous example, the program tries to access an index that does not exist on the array. The program above returns the error message as shown:

invalid array index 5 (out of bounds for 3-element array)

We can also manually raise a panic. An example is as shown below:

package main
func main() {
    lang := "Java"
    if lang != "Go" {
        panic("We only support Go Lang")
    }
}

The previous simple example checks if a variable is equal to a specified value. If true, the program does nothing. Otherwise, it panics and returns with an error message.

An example output is provided below:

panic: We only support Go Lang
goroutine 1 [running]:
main.main()
/panic.go:12 +0x27
exit status 2

Note: a deferred function will always run despite a program panic. An example can be illustrated as shown below:

package main
import "fmt"
func main() {
    defer fmt.Println("I will always run")
    lang := "Java"
    if lang != "Go" {
        panic("We only support Go Lang")
    }

}

Conclusion

This guide covered the fundamentals of working with the panic method in the Go programming language. Plus, we discussed how a programmer can manually raise a panic. We hope you found this article helpful. Check out other Linux Hint articles for more tips and tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list