How to Handle Errors in Go with if err != nil
Go has no exceptions for ordinary failures. A function that can fail returns an error as its last value, and the caller checks it straight away with if err != nil. It's the most common pattern in Go code.
Syntax
<value>, err := <functionThatCanFail>(<arguments>)
if err != nil {
// handle the error, then stop: return, or exit
}
// use <value> here
| Part | What it does |
|---|---|
<value>, err := | Receives the result and the error. |
err != nil | true when something went wrong; nil means no error. |
Inside the if | Handle it, usually by returning, so the code below only runs on success. |
The strconv documentation for Atoi says it "is equivalent to ParseInt(s, 10, 0), converted to type int", and like the other Parse functions it returns an error for text that isn't a number.
The Example
The example converts the text forty-two to a number with strconv.Atoi. That fails, so the program prints the error and stops.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import (
"fmt"
"strconv"
)
func main() {
number, err := strconv.Atoi("forty-two")
if err != nil {
fmt.Println("Not a number:", err)
return
}
fmt.Println(number)
}
strconv.Atoireturns two values: the number and anerror.if err != nilcatches the failure;returnendsmainthere, sofmt.Println(number)never runs with a bad value.
Step 2: Run It
go run main.go
Not a number: strconv.Atoi: parsing "forty-two": invalid syntax

The error message says which function failed, on what input and why. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Ignoring the error with number, _ := | A failed conversion gives 0, and the program carries on with it | Check err |
Forgetting return inside the if | The code below runs anyway, with a bad value | Return after handling the error |
Declaring err and never using it | declared and not used: err | Check it, as Go requires |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A value is 0 or empty when it shouldn't be | An error was ignored | Check the error the function returned |
declared and not used: err | err was assigned but never checked | Add if err != nil { ... } |
FAQ
Why doesn't Go use exceptions?
Errors are ordinary values in Go, so failures show up in the function's signature and are handled where they happen. Go keeps panic for truly unexpected situations.
How do I add context to an error?
Wrap it: fmt.Errorf("reading the price: %w", err) keeps the original error inside a clearer message.
Conclusion
A Go function that can fail returns an error. Check it with if err != nil right after the call, handle it, and return, so the rest of the code only sees good values.
Additional Resources
- Error handling and Go, on the Go blog.
- strconv.Atoi, in the Go standard library documentation.
