Golang in sixty seconds — panic

Richard Bell
1 min readAug 10, 2022
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 the recover 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 after panic as it will terminate the program. We therefore need to make use of the defer statement 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 see AAAH! 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.

More Golang in sixty seconds

Get Unlimited access to Medium

Buy me a coffee if you enjoyed the article :)

--

--

Richard Bell
Richard Bell

Written by Richard Bell

Father to two beautiful baby girls | Husband to a generous wife | Lead Software Engineer | Hobby collector | Support me at ko-fi.com/richardtbell

No responses yet