Introduction to Error Handling
Start with Introduction to Error Handling
Go commonly reports expected failures as values returned by functions. The caller decides how to handle those failures.
What you’ll learn
- Explain the main purpose of introduction to error handling.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A function often returns (result, error). An error value of nil means no error was reported; a non-nil error describes failure. Check it immediately before using the result.
Errors are ordinary values, not automatically thrown exceptions. Reserve panic for cases where normal error handling is inappropriate; invalid input and missing resources are usually ordinary errors.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"errors"
"fmt"
)
func positive(n int) (int, error) {
if n <= 0 {
return 0, errors.New("number must be positive")
}
return n, nil
}
func main() {
value, err := positive(5)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Value:", value)
_, err = positive(-2)
if err != nil {
fmt.Println("Error:", err)
}
}
Output
Value: 5
Error: number must be positiveTrace what the program does
The valid call returns 5 and nil, so the program prints the value. The second call returns a non-nil error and the program prints its message instead of treating the zero result as success.
Avoid common mistakes
- Do not ignore a returned error and assume the primary result is valid.
- Expected invalid input generally belongs in a returned error rather than a panic.
Try it yourself
Change positive to accept only values greater than 10, then test both success and failure.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Introduction to Error Handling in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.