Skip to content

Chapter 10: Errors (The Guard Rails) ​

Goal: Learn how to say "No" safely. Concept: In Go, errors are not "Exceptions" that crash your program. They are just values, like a string or an integer. Generally, they are the polite refusal of a function to do what you asked.

1. The Logic of "Maybe" ​

For recoverable failures, many Go functions return a result and an error. Not every function has this signature, and Go also has panics. Our example returns:

  1. The Result (if successful)
  2. The Error (if failed)
go
func Divide(a, b int) (int, error) {
    if b == 0 {
        // We cannot divide by zero. Return 0 and an error.
        return 0, fmt.Errorf("cannot divide by zero")
    }
    // Success! Return result and nil (no error).
    return a / b, nil
}

2. strict "if err != nil" ​

The most famous pattern in Go. You will type this thousands of times. Memorize the rhythm.

go
result, err := Divide(10, 0)
if err != nil {
    // 🚨 HANDLE IT!
    fmt.Println("Error:", err)
    return
}
// ✅ PROCEED
fmt.Println("Result:", result)

IMPORTANT

The Golden Rule: Never ignore an error. Even if you think "it will never happen." It will.

3. Visual Signal: The Fork in the Road 🛤️ ​

Imagine a railroad switch.

  • Main Track: The Happy Path (Success).
  • Side Track: The Error Path.

Every time you call a function that returns an error, you are at a switch. You MUST decide where the train goes.

4. What this pattern guarantees ​

Returning an error makes the failure path visible. Go does not force callers to check every returned error. You must decide whether to handle it or return it with context. Exceptions in other languages can also be handled safely; this chapter teaches the Go convention, not a guarantee that one language prevents mistakes.

Checkpoint ​

  • Always check if err != nil.

5. Visual Signal: The Highway Guard Rail ​

Concept: Early Return / Error Handling. Signal: A highway guard rail. If you drift off course (Error), it stops you immediately before you fall off the cliff (Crash).

Released under the MIT License.