Before giving examples of error handling in various languages, I want to introduce the Gotime Podcast. I highly recommend listening to their conversation around Go’s debates on whether or not to add try to the language.

golang.org explains error handling in the following way:

In Go, it’s idiomatic to communicate errors via an explicit, separate return value. This contrasts withthe exceptions used in languages like Java and Ruby and the overloaded single result / error value sometimes used in C. Go’s approach makes it easy to see which functions return errors and to handle them using the same language constructs employed for any other, non-error tasks.

Here are some of my takeaways:

  • Errors are treated as 2nd class citizens in many programming languages, but in Go they’re 1st class.

    Go Error Example

  • “Self-taught” developers without computer science knowledge often dismiss the importance of handling errors, either because they didn’t learn how to do it properly or they’re more concerned with the business logic of the thing.

    I liked this hot take.

    Personally, I didn’t learn much about errors in my coding bootcamp four years ago. The learning intention was quick iteration - wireframe it, figure out what data needed to be stored, and hook it all up in a way that “works.” I’d love to know if you had a different experience.

    In getting my associates in computer science, I am now learning the importance and techniques behind error writing.

  • An argument against adding try functionality in Go, is that it’s syntatically harder to read when visually reviewing code.

    While programming languages work in the way they’re written, humans will choose to write in the ways they find most understandable.

    Unfortunately, this means that codebases would blossom with both error handling techniques and might tilt the scale to more confusing vs. attempting to force a more accepted programming functionality simply because a lot of people are aware of it.

  • It’s hard to make big decisions for an entire programming community. It’s hard to know how everyday programmers are using error handling in Go.

    Carmen Andoh had a great quote which summs this up towards the end: “We’re thinking about this idea of inclusion, and inclusion will always have tradoffs, it’s a paradox. Do we include people intrenched in other programming languages into the Go fold at the cost of alienating Go programmers? That’s a really hard question to answer.”

Code examples

Python

In this example we’re using the system package and attempting to open a file, read a line and return a copy of the string casted to an integer with both leading and trailing characters removed.

The errors or exceptions we’re handling are an OSError, a ValueError or a general unexpected error. This is an example of using try, which most languages utilize.

import sys
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

Golang

In Go errors are values, and what can we do with values in functions? Assign them! Return them! Whatever you need to do, depending on whether you’re retruning an error from an external package or not.

import "errors"
func run(files []string) error {
    for _, file := range files {
        if err := runfile(file); err != nil {
            return errors.Wrap(err, file)
        }
    }
    return nil
}

In utilizing the Go way, you can insert an error hander inside of a loop so that you know which item caused the error.

Happy coding!

E


Got Questions❓, Comments 🗣 or Edits ✍

Use the Twitter thread below and hashtag #E4Everything to get in touch with me regarding this blog post:

Previous: Arrow FunctionsNext: Naming Things