Beginner Fundamentals
Errors
Go does not use exceptions. Instead, functions return an error value, and the caller checks it. This makes failure handling explicit.
The error type
error is a built-in type. A nil error means success; a non-nil error describes what went wrong.
Returning an error
Use errors.New to create a simple error. Return it alongside the result.
import (
"errors"
"fmt"
)
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
Checking errors
The common pattern is if err != nil.
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
Formatting errors
fmt.Errorf builds an error with formatted text.
name := "config.txt"
err := fmt.Errorf("could not open %s", name)
fmt.Println(err) // could not open config.txt
Checking errors right where they happen keeps Go programs predictable and robust.