Module 2 · Lesson 5 of 510/50 in the course~12 min
Module lessons (5/5)
Errors: the `if err != nil` pattern
Lesson preview5 hands-on exercises readyCourse Go · Module 2 — Flow Control
Errors are values; the fundamental pattern if err != nil { return err } and why Go has no exceptions.
What you'll learn in this lesson
- Treat errors as explicit values handled with the
if err != nilpattern. - Create new errors with
errors.Newand add context via wrapping (fmt.Errorf("...: %w", err)). - Compare sentinel errors robustly with
errors.Iswithout usingpanicfor ordinary errors.
Overview
Go does not have try and catch: functions that can fail return a error as the last return value. An error nil reports success; any value not nil forces the caller to handle it explicitly where it occurs.
A sentinel error is a Err... variable exported from a package to indicate known conditions (e.g. os.ErrNotExist, io.EOF):
Sections covered in this lesson
- 1The built-in interface
error - 2The fundamental pattern
if err != nil - 3Constructing and Wrapping Errors (
errors.Newand%w) - 4Sentinel error and comparison with
errors.Is - 5Quick Guards with
errors.Join(Go 1.20+) - 6Guided practice
Pro Lesson · Module 2 — Flow Control
Unlock "Errors: the `if err != nil` pattern" and the full Course Go curriculum
Errors are values; the fundamental pattern `if err != nil { return err }` and why Go has no exceptions.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.