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:
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
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:
We can also manually raise a panic. An example is as shown below:
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:
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:
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.