What is panic() in Golang?

The panic() function in Go Language is similar to exceptions raised at runtime when an error is encountered. panic() is either raised by the program itself when an unexpected error occurs or the programmer throws the exception on purpose for handling particular errors.

The panic() function is inbuilt in Go Language and when it is raised, the code prints a panic message, and the function crashes. If there are other goroutines ongoing, they function normally and return. Once all goroutines have returned, the program crashes. Below is the prototype of the panic() function:

func panic(v interface{})

Parameters

The panic() function, if used deliberately by a programmer, can be given an input of the error message that the programmer wishes to print on the screen when a panic occurs.

Example

Below is an example of how panic() is raised by a program itself:

Panic raised by program

package main
import "fmt"
func main() {
emp := make(map[string]int)
emp["Samia"] = 20
emp["Sana"] = 23
fmt.Println(emp[20])
}

Explanation

In the code above, the error is raised because the code tries to access the map’s elements through a key of type int, whereas the map elements can only be accessed through keys of type string.

Panic raised by programmer

Below is an example of when a programmer raises panic on purpose:

package main
func employee(name *string, age int){
if age > 65{
panic("Age cannot be greater than retirement age")
}
}
func main() {
empName := "Samia"
age := 75
employee(&empName, age)
}

Explanation

As shown in the code above, we call the employee function from the main function. We give the employees name and age as input. The employee function raises panic if the employee’s age is greater than the retirement limit.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved