Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang

What is panic() in Golang?

Samia Ishaque

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

golang

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring