๐ŸŽ“ A1Learner
๐Ÿ”

Go Errors

An error is a value that reports a problem. A function returns an error value beside its normal result.

Return an Error

Divide returns an int and an error. A zero divisor gives the error path.

package main

import "fmt"
import "errors"

func divide(a int, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("cannot divide 10 by zero")
	}
	return a / b, nil
}

func main() {
	_, err := divide(10, 0)
	if err != nil {
		fmt.Println(err)
	}
}

The Success Path

A divisor of 2 is fine, so the error comes back nil. The quotient then prints.

package main

import "fmt"
import "errors"

func divide(a int, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("cannot divide 10 by zero")
	}
	return a / b, nil
}

func main() {
	q, err := divide(10, 2)
	if err == nil {
		fmt.Println(q)
	}
}

An Error From a Package

Atoi reads text as a number, and the text abc is not a number. Its error prints in full.

package main

import "fmt"
import "strconv"

func main() {
	n, err := strconv.Atoi("abc")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(n)
	}
}

A Runtime Panic

The slice has length 3, so index 5 does not exist. The program panics and ends.

package main

import "fmt"

func main() {
	nums := []int{1, 2, 3}
	fmt.Println(nums[5])
}

Defer Runs Last In, First Out

Two calls are deferred in main. They run at the end of main, in reverse order.

package main

import "fmt"

func main() {
	defer fmt.Println("first deferred")
	defer fmt.Println("second deferred")
	fmt.Println("main body")
}

Example

package main

import "fmt"
import "errors"

func divide(a int, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("cannot divide 10 by zero")
	}
	return a / b, nil
}

func main() {
	_, err := divide(10, 0)
	if err != nil {
		fmt.Println(err)
	}
	q, err := divide(20, 4)
	if err == nil {
		fmt.Println(q)
	}
	fmt.Println("Program continues.")
}

Key points

  • Error: a value that reports a problem.
  • A function returns an error beside its normal result.
  • A nil error means no problem happened.
  • Check the error value before trusting the other result.
  • Use errors.New to build an error value from a message.
  • Panic: a runtime failure that ends the program.
  • Defer schedules a call to run at the end of the current function.
  • Deferred calls run in last-in, first-out order.

In this example, the first call divides 10 by 0 and returns an error. Main prints that error and keeps going. The second call divides 20 by 4 and returns a nil error. Main prints the quotient 5. The last line shows the program running on after an error.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

A function returns a result and an error, and the error is nil. What does nil mean here?