Thuta Learning
AdvancedProgrammingbeginner

Error Handling

Relax. We'll talk through this in plain words — no textbook voice.

Instead of exceptions, Go's normal style is to return an error value and have the caller check it. This approach keeps errors from hiding — you can see them clearly right in the code flow.

go
package main

import (
    "errors"
    "fmt"
)

func divide(a int, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Result:", result)
}

divide function returns a result and an error. When there's no error, it returns nil; when there is one, it returns an error value carrying a message.

You should see
Error: cannot divide by zero

Info

if err != nil might look repetitive once you notice it everywhere, but it's an important style for keeping Go code readable.

Easy traps

  • Ignoring errors can lead to serious production bugs. At the very least, log it, show a user-friendly message, or pass it back to the caller.