avatarRichard Bell

Summary

In Golang, the panic function triggers a runtime error, and while it can be paired with recover for error handling, it should be used judiciously as it terminates the program; instead, returning errors is often preferable.

Abstract

The panic function in Go is designed to cause a runtime error, which can be useful for exceptional situations when combined with the recover function to handle errors gracefully. However, it's important to note that panic will immediately stop the program's execution, so any code following a panic call will not be executed unless it is deferred. To properly use recover, it should be placed within a deferred function to ensure it runs even after a panic. This allows the program to output the panic value and continue executing other deferred calls before terminating normally. Despite its utility, the use of panic should be limited to circumstances where a crash is justified, such as when an unrecoverable error occurs. In most cases, it is more appropriate to return an error to the caller, allowing for more controlled error handling without causing the program to terminate abruptly.

Opinions

  • The author suggests that panic should be used sparingly, implying that it is not suitable for common error handling.
  • There is an emphasis on using defer in conjunction with recover to handle panics, indicating a best practice for error handling in Go.
  • The author

Golang in sixty seconds — panic

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 :)

Golang
Learning To Code
Golang Tutorial
Software Development
Programming
Recommended from ReadMedium