Error Handling in Go
Handle errors clearly and safely using Go's error values.
Learning objective: Return and check error values in a simple function.
Go Error Style
Go handles errors using returned error values rather than exceptions. This makes error handling explicit.
Checking Errors
Always check whether an error has occurred before using a result that may not be valid.
Creating Errors
You can create your own error messages using the errors package.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import (
"errors"
"fmt"
)
func divide(a float64, b float64) (float64, 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)
}
Key points to remember
- A nil error means no error occurred.
- Check errors immediately after calling a function that can fail.
- Clear error messages help users and developers understand the problem.
Practice Exercises
- Create a divide function.
- Return an error when input is invalid.
- Check and print error messages.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.