Go Tutorial: Error Handling
Go handles errors differently — and better. No exceptions, no surprises. Just values you check and handle.
No exceptions. Just values.
In most languages, errors are exceptions — they fly up the call stack, crash your program, or get silently swallowed.
Go takes a different approach. Errors are just values. A function that can fail returns two things: the result and an error. You check the error. You handle it. You move on.
It feels verbose at first. But it makes every failure path explicit — you always know exactly where things can go wrong and exactly what happens when they do.
This is one of Go's most defining features. Thirteen steps.
What you'll learn in this Go error handling tutorial
This interactive Go tutorial has 13 hands-on exercises. Estimated time: 24 minutes.
- What is an error in Go — In Go, `error` is a built-in type. It is actually an interface with one method: `Error() string`.
- Checking an error — if err != nil — The most common pattern in all of Go:
- errors.New() — create your own error — You can create your own error values using `errors.New()`:
- fmt.Errorf() — errors with context — `fmt.Errorf` creates an error with a formatted message — like `fmt.Sprintf` but returns an `error`.
- Ignoring errors — the dangerous shortcut — You can ignore the error return value with `_`. Go will not stop you.
- Multiple error checks in one function — A function can have multiple failure points. Check each one and return the first error you find.
- Custom error types — Sometimes you need more than a message. You want a structured error you can inspect programmatically.
- errors.Is() — identify a specific error — When a function can return different errors, you sometimes need to know which one you got.
- errors.As() — extract the error type — `errors.As` checks if an error is a specific type and extracts it so you can read its fields.
- Wrapping errors — add context without losing the original — When your function calls another function that fails, wrap the error to add context:
- panic and recover — `panic` stops normal execution immediately. Use it only for truly unrecoverable situations — programming bugs, impossibl…
- Fix the broken error check — This program is supposed to read a number and double it. But it ignores the error — so when the input is invalid it sile…
- Build a user validator — No starter code.
Go Error Handling concepts covered
- No exceptions. Just values.