Golang in sixty seconds — panic
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.
Get Unlimited access to Medium
Buy me a coffee if you enjoyed the article :)