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 11 hands-on exercises. Estimated time: 24 minutes.
- What is an error in Go — Most languages throw exceptions — like fire alarms that scream until someone handles them. Go is different: functions re…
- Checking an error — if err != nil — The most common pattern in all of Go: `if err != nil { ... }`.\nAdd a check: if `strconv.Atoi` returns an error, print `…
- ahha — errors.New() creates your own errors — You can create your own error values using `errors.New()`.\n`return 0, errors.New("book not found")`\nAdd an error case …
- fmt.Errorf() — errors with context — `fmt.Errorf` creates an error with a formatted message — like `fmt.Sprintf` but returns an `error`.\n`return fmt.Errorf(…
- Custom error types — Sometimes you need more than a message — a structured error you can inspect programmatically.\nDefine a struct with an `…
- errors.Is() — identify a specific error — `errors.Is(err, ErrBookNotFound)` checks if `err` matches a specific sentinel error.\nA sentinel error is a package-leve…
- 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.\n`var le LibraryError; if …
- Wrapping errors with %w — When your function calls another function that fails, wrap the error to add context:\n`return fmt.Errorf("processBook: %…
- panic and recover — `panic` stops normal execution immediately. Use it only for truly unrecoverable situations.\n`recover` catches a panic i…
- Fix the broken error check — This program ignores the error — so when the ID is invalid it silently shows an empty string.\nFix it: check the error f…
- Build a library validator — No starter code. Build a library item validator with a custom error type:\n1. Define `CatalogError` with `Field` and `Me…
Go Error Handling concepts covered
- No exceptions. Just values.