Introduction
Panic and Recover are part of the Go error handling techniques. For some readers, the concept of Panic and Recover is always very confusing. However, it is not confusing at all. In this article, we will learn all about panic and how we can recover from it.
Panic is equivalent to raising an exception in some other programming languages( like Java), whereas Recover can be thought of as catching the exception.
We shall first discuss panic and then recover.
Panic
Panic is used to exit a program when it detects abnormal conditions.
Panic is a built-in function that causes the normal flow of control to stop and panic to begin. When any function (say f()) calls panic, the execution of function f() is halted, any deferred functions inside function f() are executed normally, and then it returns to its caller.
Panics are generated mainly because of two reasons:
- Any runtime error, such as index out of bounds error, happens when an index larger or lesser than the size of the array is accessed.
- If the panic function is explicitly called in the program.
Syntax and example of panic
Syntax:
func panic(v interface{})
Example:
package main
func main() {
panic("Panic is explicitly called.....")
}
Output:
panic: Panic is explicitly called.....
goroutine 1 [running]:
main.main()
/home/main.go:5 +0x39
Panic Due to Runtime Error
Runtime errors can occur in situations like:
- Accessing an index in an array that is not available. It is known as an array index out of bounds/range error.
- When a function is called with a nil pointer.
- Sending on a closed channel.
- When there is incorrect type assertion.
Example:
package main
import "fmt"
func main() {
// declare a slice of lenght 2. The contents are
// Coding and Ninjas
company := []string{"Coding", "Ninjas"}
//prints company[0] -> Coding
fmt.Println(company[0])
// prints company[1] -> Ninjas
fmt.Println(company[1])
// trying to access index 2 which does not exist
// will result in a panic
fmt.Println(company[2])
}
Output:
Coding
Ninjas
panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
/home/main.go:19 +0x12a
Calling the Panic function explicitly.
There are certain situations where the programmers call the panic function explicitly in the program. One of the most common scenarios is when a certain input is expected as a parameter; however, nil is passed. In such a case, the programmer puts a check that if a nil value is passed, raise a panic.
Example:
package main
import "fmt"
func main() {
//create a slice named company
company := []string{"Coding", "Ninjas"}
//printing the content of company[] before called noNilAllowed()
fmt.Println(company[0],company[1])
fmt.Println() // to add an extra line
//pass nil as the value to noNilAllowed()
noNilAllowed(nil)
}
// function that does not allows nil parameters
func noNilAllowed(company[] string){
if company==nil{
// creating a panic if nil is passed
panic("Nil value supplied. Program halted!")
}else{
fmt.Println("supplied value is: ", company)
}
}
Output:
Coding Ninjas
panic: Nil value supplied. Program halted!
goroutine 1 [running]:
main.noNilAllowed(...)
/home/main.go:25
main.main()
/home/main.go:15 +0x13a