Named returns
If you are not familiar with what a named return is, reference A Tour of Go Basics.
Named returns... Hurk...
I know, I know... Named returns can decrease the readability of longer functions written in Golang, but there is a case in which they are a necessity. Handling panics gracefully!
Problem
In many languages, you might use a try/catch block to handle some code that might otherwise throw an exception and wreak havoc. They allow us to override any values. In Golang, we have panics.
First, let's create a simple function that divides 2 integers:
func Divide(numerator, denominator int) (int, error) {
return numerator / denominator, nil
}
The issue with this code is that we cannot divide by 0
. Doing so will result in: panic: runtime error: integer divide by zero
.
We could have a check for whether the denominator is 0
, but for the purposes of this post, how can we gracefully handle this panic?
Solution
Here's a refresher on panic, defer, and recover.
By naming the return values, val
and err
respectively, we can recover from the panic and return any value and error we would like.
func Divide(numerator, denominator int) (val int, err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
return numerator / denominator, nil
}
Now, instead of needing to handle the panic everywhere Divide
is called, callers can simply handle the graceful error.
Top comments (0)