Using named return variables to capture panics in Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This was going to was a short post inspired by Sean Kelly's tweet in November.

I found a reason to use named returns in #golang and now I feel PIC.TWITTER.COM/6EN3VAPUHB

-sean Kelly (@StabbyCutyou) November 15, 2017

The goal is to just document and illustrate a situation where named return variables be necessary, so with this said let ' s just jump right in.

Imagine You is writing some code that uses a function so can panic, and for whatever reason (3rd party lib, backwards c Ompatibility, etc) you can ' t change this function.

func pressButton() {    fmt.Println("I'm Mr. Meeseeks, look at me!!")  // other stuff then happens, but if Jerry asks to   // remove 2 strokes from his golf game...  panic("It's gettin' weird!")}

You still need to use this function, but if it panics you want to capture the panic and return it as a error so you write Some code like this:

func doStuff() error {    var err error  // If there is a panic we need to recover in a deferred func  defer func() {    if r := recover(); r != nil {      err = errors.New("the meeseeks went crazy!")    }  }()  pressButton()  return err}

Run it on the Go PLAYGROUND-HTTPS://PLAY.GOLANG.ORG/P/WZKJKGQFPL

Then you go run your code and ... What's this? Your error is nil even when the code panics? That's not what we wanted!

Why does this happen?

While at first it looks like our code var err error is returning the-we create at the start of our function, the truth are our Program never gets to that line of code. This means it never actually returns that specific err variable, and altering it inside of we deferred function ends up Being pointless.

Adding A after the call to but Println pressButton before the return really helps illustrate this:

pressButton()  // Nothing below here gets executed!fmt.Println("we got here!")  return err  

Run it on the Go playground-https://play.golang.org/p/vk0dys20eb

How do we fix it?

To fix the issue, we can simply use a named return variable.

func doStuff() (err error) {      // If there is a panic we need to recover in a deferred func    defer func() {        if r := recover(); r != nil {            err = errors.New("the meeseeks went crazy!")        }    }()    pressButton()    return err}

Run it on the Go playground-https://play.golang.org/p/bqgoropjqj

The resulting code looks very similar, but by naming we return variable when we declare the function our program would now Return the err variable even if we never hit the return statement at the end of our doStuff function. Because of this minor difference, we can now alter the err variable inside of our deferred function and successfully cap Ture the panic.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.