Lesson 28 of 38 · Interfaces & Errors
Go Error Handling: error Values and if err != nil
Go has no exceptions. A function that can fail says so in its signature by returning an error, and the caller decides — right there, in plain code — what to do about it. Go error handling looks wordy at first, but you always see exactly where things can go wrong and what happens when they do.
The error interface
error is a built-in interface with a single method:
type error interface {
Error() string
}
Any type with an Error() string method is an error — implicit interfaces at work again. A nil error means "no error".
Creating errors
errors.New creates an error with a fixed message; fmt.Errorf formats one, just like fmt.Sprintf:
err := errors.New("bridge is broken")
fmt.Println(err)
err = fmt.Errorf("level %d is locked", 3)
fmt.Println(err)
bridge is broken
level 3 is locked
Returning (value, error)
By convention the error is the last result. On failure, return the zero value for every other result plus the error. On success, return the value and nil:
func Divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
Check errors immediately
Check err on the very next line and return early. The happy path stays at the left margin, while each failure is handled in a short if block:
n, err := strconv.Atoi("42x")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(n * 2)
error: strconv.Atoi: parsing "42x": invalid syntax
strconv.Atoi is a typical standard library function returning (int, error). When err is not nil, treat the other results as meaningless — here n is just 0.
Sentinel errors and errors.Is
When callers need to react to one specific failure, declare it once as a package-level sentinel error. By convention its name starts with Err:
var ErrNotFound = errors.New("not found")
func FindScore(scores map[string]int, name string) (int, error) {
score, ok := scores[name]
if !ok {
return 0, ErrNotFound
}
return score, nil
}
func main() {
_, err := FindScore(map[string]int{"ana": 30}, "bo")
if errors.Is(err, ErrNotFound) {
fmt.Println("no such player")
}
}
no such player
Here errors.Is(err, ErrNotFound) gives the same answer as err == ErrNotFound, but it keeps working when the error has been wrapped with extra context — the topic of the next lesson. Make it a habit.
Writing good error messages
Error messages start with a lowercase letter and have no final punctuation, because they are often chained together: load save: open file: permission denied. Say what failed and include the values that help, as in level 3 is locked.
Errors, not panics
panic is for bugs that should never happen. Bad user input, a missing file or a network timeout are expected failures: return an error and let the caller decide what to do.
Common mistakes
- Ignoring errors:
n, _ := strconv.Atoi(s)silently turns bad input into0. - Using the result before checking
err: check first, then use the value. - Comparing messages:
err.Error() == "not found"breaks as soon as the wording changes. Compare with a sentinel usingerrors.Is. - Capitalised messages with punctuation:
"File not found."reads badly once it's chained. - Mixed signals: returning a non-nil error on success, or a meaningful-looking value together with an error.
Assignment
The starter declares three sentinel errors: ErrNegativeAge, ErrInvalidAmount and ErrInsufficientFunds.
ParseAge(s string) (int, error)converts text to an age:- if
strconv.Atoifails, return0and its error unchanged (add"strconv"to the imports); - a negative number returns
0, ErrNegativeAge; - a number above
150returns0and an error with the messageage 151 is too high(with the actual number) — usefmt.Errorf; - otherwise, return the age and
nil.
- if
Withdraw(balance, amount int) (int, error)returns the new balance:- an
amountof0or less returns0, ErrInvalidAmount; - an
amountgreater thanbalancereturns0, ErrInsufficientFunds; - otherwise, return
balance - amount, nil.
- an
ParseAge("42") // 42, nil
ParseAge("forty") // 0, strconv.Atoi: parsing "forty": invalid syntax
ParseAge("-5") // 0, ErrNegativeAge
ParseAge("151") // 0, age 151 is too high
Withdraw(100, 30) // 70, nil
Withdraw(20, 50) // 0, ErrInsufficientFundsPremium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Errors and exceptions in other languages
- JavaScript Error Handling: try, catch and Custom Errors · JavaScript
- Python Exceptions: try, except, else and finally · Python
- Java Exceptions: try, catch, finally and Custom Exceptions · Java
- C# Exceptions: try, catch, finally and Custom Exceptions · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .