In Go language, panic is just like an exception, it also arises at runtime. Or in other words, panic means an unexpected condition arises in your Go program due to which the execution of your program is terminated. Sometimes panic occurs at runtime when some specific situation arises like out-of-bounds array accesses, etc. as shown in Example 1 or sometimes it is deliberately thrown by the programmer to handle the worst-case scenario in the Go program with the help of
panic() function as shown in Example 2.
The panic function is an inbuilt function which is defined under the builtin package of the Go language. This function terminates the flow of control and starts panicking.
Syntax:
func panic(v interface{})
It can receive any type of argument. When the panic occurs in the Go program the program terminates at runtime and in the output screen an error message as well as the stack trace till the point where the panic occurred is shown. Generally, in Go language when the panic occurs in the program, the program does not terminate immediately, it terminates when the go completes all the pending work of that program.
For Example, suppose a function A calls panic, then the execution of the function A is stopped and if any deferred functions are available in A, then they are executed normally after that the function A return to its caller and to the caller A behaves like a call to panic. This process continues until all the functions in the current goroutine are returned, after that the program crashes as shown in example 3.
Example 1:
C
// Simple Go program which illustrates
// the concept of panic
package main
import "fmt"
// Main function
func main() {
// Creating an array of string type
// Using var keyword
var myarr [3]string
// Elements are assigned
// using an index
myarr[0] = "GFG"
myarr[1] = "GeeksforGeeks"
myarr[2] = "Geek"
// Accessing the elements
// of the array
// Using index value
fmt.Println("Elements of Array:")
fmt.Println("Element 1: ", myarr[0])
// Program panics because
// the size of the array is
// 3 and we try to access
// index 5 which is not
// available in the current array,
// So, it gives an runtime error
fmt.Println("Element 2: ", myarr[5])
}
Output:
./prog.go:32:34: invalid array index 5 (out of bounds for 3-element array)
Example 2:
C
// Go program which illustrates
// how to create your own panic
// Using panic function
package main
import "fmt"
// Function
func entry(lang *string, aname *string) {
// When the value of lang
// is nil it will panic
if lang == nil {
panic("Error: Language cannot be nil")
}
// When the value of aname
// is nil it will panic
if aname == nil {
panic("Error: Author name cannot be nil")
}
// When the values of the lang and aname
// are non-nil values it will print
// normal output
fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)
}
// Main function
func main() {
A_lang := "GO Language"
// Here in entry function, we pass
// a non-nil and nil values
// Due to nil value this method panics
entry(&A_lang, nil)
}
Output:
panic: Error: Author name cannot be nil
goroutine 1 [running]:
main.entry(0x41a788, 0x0)
/tmp/sandbox108627012/prog.go:20 +0x140
main.main()
/tmp/sandbox108627012/prog.go:37 +0x40
Example 3:
C
// Go program which illustrates the
// concept of Defer while panicking
package main
import (
"fmt"
)
// Function
func entry(lang *string, aname *string) {
// Defer statement
defer fmt.Println("Defer statement in the entry function")
// When the value of lang
// is nil it will panic
if lang == nil {
panic("Error: Language cannot be nil")
}
// When the value of aname
// is nil it will panic
if aname == nil {
panic("Error: Author name cannot be nil")
}
// When the values of the lang and aname
// are non-nil values it will
// print normal output
fmt.Printf("Author Language: %s \n Author Name: %s\n", *lang, *aname)
}
// Main function
func main() {
A_lang := "GO Language"
// Defer statement
defer fmt.Println("Defer statement in the Main function")
// Here in entry function, we pass
// one non-nil and one-nil value
// Due to nil value this method panics
entry(&A_lang, nil)
}
Output:
Defer statement in the entry function
Defer statement in the Main function
panic: Error: Author name cannot be nil
goroutine 1 [running]:
main.entry(0x41a780, 0x0)
/tmp/sandbox121565297/prog.go:24 +0x220
main.main()
/tmp/sandbox121565297/prog.go:44 +0xa0
Note: Defer statement or function always run even if the program panics.
Usage of Panic:
- You can use panic for an unrecoverable error where the program is not able to continue its execution.
- You can also use panic if you want an error for a specific condition in your program.
Similar Reads
Packages in Golang
Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. This modula
5 min read
Parsing Time in Golang
Parsing time is to convert our time to Golang time object so that we can extract information such as date, month, etc from it easily. We can parse any time by using time.Parse function which takes our time string and format in which our string is written as input and if there is no error in our form
2 min read
fmt Package in GoLang
Prerequisite: Packages in GoLang and Import in GoLang Technically defining, a package is essentially a container of source code for some specific purpose. Packages are very essential as in all programs ranging from the most basic programs to high-level complex codes, these are used. A package ensur
13 min read
Templates in GoLang
Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates: text/template html/template There are mainly 3 parts of a template which are as follows: 1. Actions They are data evaluations, control structures like loops
4 min read
math Package in Golang
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. FunctionDescriptionAbsThis function is used to return the absolute value of the specified number.AcosThis function returns the arccosine, in ra
7 min read
bits Package in Golang
Go language provides inbuilt support for bit counting and manipulation functions for the predeclared unsigned integer types with the help of the bits package. .bits-package-Golang-table { border-collapse: collapse; width: 100%; } .bits-package-Golang-table td { border: 1px solid #5fb962; text-align:
6 min read
Recover in Golang
Just like try/catch block in exception in languages like Java, C#, etc. are used to catch exception similarly in Go language, recover function is used to handle panic. It is an inbuilt function which is defined under the builtin package of the Go language. The main use of this function is to regain
4 min read
string package in Golang
Go language provides a string package that holds different types of functions to manipulate UTF-8 encoded strings. To access the function of the string package you need to import a string package in your program with the help of the import keyword.  FunctionDescriptionfunc CompareThis function is u
8 min read
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOSÂ Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protect
9 min read
strconv package in Golang
Go language provides a strconv package that implements conversions to and from string representations of basic data types. To access the functions of the strconv package you need to import the strconv package in your program with the help of the import keyword. .strconv-golang-table { border-collaps
5 min read