Explaining Go error handling

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

I recently translated great article-errors is values by Rob Pike-and We discussed it in our podcasts golangshow (in RU Ssian). One thing I was surprised about are that even experienced Go developers sometimes does not understand the core idea of a Rticle.

Looking back, I remember my first impressions if I read it for the first time. It is similar to "it looks like Pike just adds some complexity to what could ' ve been solved gracefully with exception S ". I had never been fond of exceptions, but that ' s the first thought I remember. The example in the article is clearly asking for comparison with exceptions ' "" to deal with errors and it didn ' t look l Ike a winner here.

Still I knew, there must be something more profound in these words- "errors is values". After all, I am always comfortable with Go errors handling, so I gave some time to myself to absorb the article.

And then I got it.

Go doesn ' t want us to treat errors as something different from our main code. Erroneous situation is a first-class citizen in program flow design.

Errors shouldn ' t is hidden or ignored in the same the "as you don't hide or ignore any other code." They is part of your logic and code.

Just try to imagine your the thinking when you deal with usual concepts-values, conditions, loops etc., and apply it to the errors. Errors is the same level entities as the rest of your code. You don ' t ignore return values of the other types for no reason, right? You don't ask language to bring special The handle Boolean variables, because "if" is boring. You don't ask yourself "What should I does, if I don ' t know what does with this slice in this abstraction level?". You just program the logic you need.

Again, errors was values, and errors ' handling is a normal programming.

Of course, there is always some patterns to deal with errors (like with any other programming conception), but they Emerg E naturally and fit perfectly in the existing language capabilities.

Let's try to illustrate it with a example, close enough to that one in the original article. Say, you had a task-"make repetitive writes with IO. Writer and calculate number of bytes written, and stop after 1024-th byte ". You start with straightforward approach:

var count, n intn = write(“one”)count += nif count >= 1024 {    return}n = write(“two”)count += nif count >= 1024 {    return}// etc

Http://play.golang.org/p/8033Wp9xly

Of course, you instantly see what's wrong with this code and, following DRY principle, you decide to deduplicate code, MOV ing repeating parts to separate function or closure:

var count intcntWrite := func(s string) {  n := write(s)  count += n  if count >= 1024 {    os.Exit(0)  }}cntWrite(“one”)cntWrite(“two”)cntWrite(“three”)

Http://play.golang.org/p/Hd12rk6wNk

Now it's better, but still not perfect. You still need a closure, which depends on external variable. It also uses OS. Exit (), which makes it hardly reusable after first refactoring. We can do better. Let's see how our thoughts flow-we has a write function, which does something else, except just writing bytes and we NE Ed it to be reusable and isolated entity. Let's refactor our code:

type cntWriter struct {    count int    w io.Writer}func (cw *cntWriter) write(s string) {    if cw.count >= 1024 {        return     }    n := write(s)    cw.count += n}func (cw *cntWriter) written() int { return cw.count }func main() {    cw := &cntWriter{}    cw.write(“one”)    cw.write(“two”)    cw.write(“three”)    fmt.Printf(“Written %d bytes\n”, cw.written())}

Http://play.golang.org/p/66Xd1fD8II

Now it looks much better, we can reuse this custom writer in other functions, it's isolated and easy to test.

Now, just replace ' counter ' with ' error value ' and you'll get almost the same example as in original article about error h Andling. But take a note how easy and logical is your flow of thoughts towards this code. You wasn ' t distracted by looking for the special counting/passing features of the language. You simply is implementing the logic you need in the best possible.

This is profound enough and could are hard-to-grasp, especially with the mindset-focused on the ' right ' to Hand Le Errors. It definitely takes some time to absorb.

Of course, it ' s debatable, and I can find both a lot of pros and cons for this approach, as well as for others. We ' re not in the Black&white world, but Go approach to errors are kind of mature and fresh at the same time, it extreme Ly simple and hard to understand at the same time, it requires some rethinking and effort to get the idea. But, what's more important, it works great in practice.

And once you get it, you stop fight the language. You stop looking for special ways to handle or hide errors. Go makes you respect errors as any other part of the Your program. You just handle them, without expecting language does the magic for you. In the long run, your code becomes better, even if does not realize it yet.

Now, come and read this article again-errors is Values-and try to get the gist of it with this perspective.

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.