Golang in sixty seconds — panic

Empty toilet roll tube with the words “Don't panic” written on it.
Photo by Jasmin Sessler on Unsplash

We can use the panic function to cause a runtime error in Golang. This can be useful when paired with therecover function for error handling within our application. We may be tempted to use recover like this:

panic("AAAH!")
str := recover()
fmt.Println(str)

However we will never reach the line afterpanic as it will terminate the program. We therefore need to make use of thedeferstatement when using recover. This means that recover will always be called at the end of the function, even if there is a runtime error.

defer func() {
  str := recover()
  fmt.Println(str)
}
panic("AAAH!")

In this case we would seeAAAH! output to the terminal on reaching this part of our program.

panic should be used sparingly as it will terminate the program. Often it will be better to return an error instead of causing a panic. If you think that the problem you are anticipating should cause the program to crash, then use panic, otherwise create an error and return it instead.

Richard Bell

Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.