Skip to Content
Learning Go, 2nd Edition
book

Learning Go, 2nd Edition

by Jon Bodner
January 2024
Beginner
494 pages
12h 30m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Go, 2nd Edition

Chapter 9. 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 solid software engineering principles underlie Go’s approach. In this chapter, you’ll learn how to work with errors in Go. You’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 was 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. A simple function with error handling 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. ...

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

Designing Data-Intensive Applications, 2nd Edition

Designing Data-Intensive Applications, 2nd Edition

Martin Kleppmann, Chris Riccomini

Publisher Resources

ISBN: 9781098139285Errata PageSupplemental Content