Skip to Content
Learning Go
book

Learning Go

by Jon Bodner
March 2021
Beginner
375 pages
8h 59m
English
O'Reilly Media, Inc.
Content preview from Learning Go

Chapter 8. Errors

Error handling is one of the biggest challenges for developers moving to Go from other languages. For those used to exceptions, Go’s approach feels anachronistic. But there are solid software engineering principles underlying Go’s approach. In this chapter, we’ll learn how to work with errors in Go. We’ll also take a look at panic and recover, Go’s system for handling errors that should stop execution.

How to Handle Errors: The Basics

As we covered briefly in Chapter 5, Go handles errors by returning a value of type error as the last return value for a function. This is entirely by convention, but it is such a strong convention that it should never be breached. When a function executes as expected, nil is returned for the error parameter. If something goes wrong, an error value is returned instead. The calling function then checks the error return value by comparing it to nil, handling the error, or returning an error of its own. The code looks like this:

func calcRemainderAndMod(numerator, denominator int) (int, int, error) {
    if denominator == 0 {
        return 0, 0, errors.New("denominator is 0")
    }
    return numerator / denominator, numerator % denominator, nil
}

A new error is created from a string by calling the New function in the errors package. Error messages should not be capitalized nor should they end with punctuation or a newline. In most cases, you should set the other return values to their zero values when a non-nil error is returned. We’ll see an exception ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Go, 2nd Edition

Learning Go, 2nd Edition

Jon Bodner

Publisher Resources

ISBN: 9781492077206Errata PageSupplemental Content