Skip to content

Check a Returned Error

The Course
•
18 min study

Until now every value in your programs was typed by you, so it was always valid. Today the values start arriving as text from a user, and text can say anything. A program that turns "25" into a number must also decide what to do with "later". Go handles this without special syntax: a function that can fail simply returns a second result describing what went wrong.

Some functions return a value and an error. strconv.Atoi converts decimal text to an int. An error of nil means the conversion succeeded. Check err before using the value, because a failed conversion returns 0.

Predict and run

Which string fails conversion?

Predict, then run Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	for _, text := range []string{"25", "later"} {
		minutes, err := strconv.Atoi(text)
		if err != nil {
			fmt.Println("Enter a whole number")
			continue
		}
		fmt.Println(minutes)
	}
}
Check your prediction
Text
25
Enter a whole number

Add "-5" to the slice. It converts successfully, so where should a rule about durations go?

Errors are values

An error is an ordinary value, returned like any other result. nil means "no error". Anything else describes a failure, and printing it shows a message written by the function that failed. The idiom is always the same: call the function, then immediately ask if err != nil and handle the failure before touching the other result.

Read the error message Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	minutes, err := strconv.Atoi("12 min")
	fmt.Println(minutes)
	fmt.Println(err)
}
Text
0
strconv.Atoi: parsing "12 min": invalid syntax

The message names the function and quotes the input, which is useful while you are debugging. Users of your program usually need something shorter and friendlier, such as Enter a whole number, so a program often prints its own message instead of the raw error.

What Atoi accepts

Atoi is strict on purpose. It accepts an optional + or - sign followed by decimal digits, and nothing else. "25", "+25" and "-5" all convert. " 25" with a leading space fails, and so do "25.0", "25min" and the empty string "". That strictness is helpful: it means your program never silently accepts half of a mistyped value. When text might have stray spaces, trim it first, which is the next lesson.

Which texts convert? Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	for _, text := range []string{"+25", "-5", " 25", "25.0", ""} {
		_, err := strconv.Atoi(text)
		fmt.Printf("%q ok: %v\n", text, err == nil)
	}
}
Text
"+25" ok: true
"-5" ok: true
" 25" ok: false
"25.0" ok: false
"" ok: false

Two kinds of invalid

The exercise above hints at an important split. "-5" is a perfectly good number, so Atoi accepts it, but it is not a sensible reading duration. Converting text checks the format; your program still has to check the meaning. Keep the two steps separate: first convert and check err, then check the range your program needs, such as 1 to 240 minutes. Each check then has one job and one message.

Do not throw the error away

minutes, _ := strconv.Atoi(text) compiles, but it discards the only signal that the conversion failed, and minutes silently becomes 0. A zero that came from bad input looks exactly like a real zero. Ignore an error with _ only when you have a good reason and can explain it in a comment.

Handling the error

What "handle" means depends on the program. Inside a loop over input lines, the usual choice is to report the problem and continue to the next line, so one bad line does not stop the whole run. In a function, the usual choice is to return the error to the caller, which you will practice on Day 6. In both cases the happy path stays at the left margin and each failure is dealt with in a short block just after the call that produced it.

Practice

Exercise

Your turn

Convert "7" and "seven". Print the number after a success and Invalid after a failure.

Your working space Go
package main

func main() {
	// Write your code here.
}
Hint 1: the idea

Conversion errors differ from rules about which numbers you accept.

Hint 2: a first step

Import strconv and keep both results from strconv.Atoi.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	for _, text := range []string{"7", "seven"} {
		n, err := strconv.Atoi(text)
		if err != nil {
			fmt.Println("Invalid")
			continue
		}
		fmt.Println(n)
	}
}
Text
7
Invalid

continue skips the rest of the loop body after a failure, so fmt.Println(n) only runs for real numbers.

Was this article helpful?

Your response is saved on this device.