The Errors Package

The Go standard library provides an "errors" package that makes it easy to deal with errors.

Read the godoc for the errors.New()arrow-up-right function, but here's a simple example:

var err error = errors.New("something went wrong")

Assignment

Textio's software architects may have overcomplicated the requirements from the last coding assignment... oops. All we needed was a new generic error message that returns the string no dividing by 0 when a user attempts to get us to perform the taboo.

Complete the divide function. Use the errors.New() function to return an error when y == 0 that reads "no dividing by 0".

circle-info

Remember that it's conventional to return the "zero" values of all other return values when you return a non-nil error in Go.

Solution

main.go
package main

import (
	"errors"
)

func divide(x, y float64) (float64, error) {
	if y == 0 {
		//Solution
		var err error = errors.New("no dividing by 0")
		return 0, err
		//
	}
	return x / y, nil
}

🧩 Understanding var err error = errors.New("no dividing by 0")

What’s happening

  1. errors.New("no dividing by 0")

    • This creates a new error value with the message "no dividing by 0".

    • The errors package has a built-in function New() that returns an error object.

    Example:

  2. var err error

    • This declares a variable named err with the type error.

    • error is a built-in interface in Go that represents an error condition.

  3. = errors.New("no dividing by 0")

    • This assigns the new error object you created to the variable err.

So together:

means:

“Make a variable called err, which is of type error, and store inside it a new error message that says no dividing by 0.”


How it’s used in context

  • If someone tries to divide by zero, this creates an error value with a message.

  • Then it returns that error instead of doing the math.


In plain English

  • errors.New() = “Make me a simple error message.”

  • var err error = ... = “Store that message inside a variable called err that represents an error.”

  • return 0, err = “Return 0 for the result and this error to tell the caller something went wrong.”


Example Usage


Quick Summary Table

Part
Meaning

errors.New("text")

Creates a new error with a message

var err error

Declares a variable of type error

err != nil

Checks if an error occurred

return 0, err

Returns an error instead of a valid result