Returning Errors
Programs often meet problems they cannot avoid. The user types abc where a number should be, or a file is missing. Many languages handle this with exceptions, which jump out of the code when something fails. Go does something simpler. A function that can fail returns an extra result of type error, and the caller checks it with a normal if.
strconv.Atoi turns text into a whole number. It returns two results: the number and an error.
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("42")
fmt.Println(n, err)
n, err = strconv.Atoi("4x2")
fmt.Println(n, err)
}
Output:
42 <nil>
0 strconv.Atoi: parsing "4x2": invalid syntax
When the conversion works, err is nil, which means "no error". When it fails, err holds a value that describes the problem, and printing it shows its message. The number is then 0, which is only a placeholder. It is not a real result.
Checking the error
The usual Go pattern is to check err right after the call, before you use the other result:
n, err := strconv.Atoi("seven")
if err != nil {
fmt.Println("not a number:", err)
return
}
fmt.Println(n * 2)
Output:
not a number: strconv.Atoi: parsing "seven": invalid syntax
The return ends the function early, so the line that doubles n never runs with a wrong value. You will see if err != nil very often in Go code. It keeps the failure path short and easy to see.
Returning your own errors
Your own functions can return an error too. Put error as the last result type. The errors package has errors.New, which makes an error from a message. fmt.Errorf does the same, but you can put values in the message with verbs like %d, just as with fmt.Printf.
package main
import (
"errors"
"fmt"
"strconv"
)
func parseAge(text string) (int, error) {
age, err := strconv.Atoi(text)
if err != nil {
return 0, err
}
if age < 0 {
return 0, errors.New("age cannot be negative")
}
if age > 150 {
return 0, fmt.Errorf("age %d is too large", age)
}
return age, nil
}
func main() {
fmt.Println(parseAge("30"))
fmt.Println(parseAge("-4"))
fmt.Println(parseAge("200"))
fmt.Println(parseAge("old"))
}
Output:
30 <nil>
0 age cannot be negative
0 age 200 is too large
0 strconv.Atoi: parsing "old": invalid syntax
errors is imported because the code calls errors.New. fmt.Println(parseAge("30")) passes both results of parseAge straight to Println, which prints them with a space between. Look at the four return lines. On success, the function returns the age and nil. On every failure, it returns 0 and an error. When Atoi fails, parseAge simply passes that same error back to its caller.
Go programmers write error messages in lower case, with no full stop at the end. A message is often printed after other text, like not a number: ... above, so it should read well in the middle of a line.
Do not ignore errors
You can throw the error away with _. Go allows it, but now nothing tells you that the input was wrong:
n, _ := strconv.Atoi("abc")
fmt.Println(n)
Output:
0
The program carries on with 0 as if it were real data. Bugs like this are hard to find later, so check every error unless you are sure the call cannot fail.
In the exercise, finish parseScore so it returns the right value and error for each kind of input.