Section 5 of 12
Error Handling
Proper error handling patterns in Go
Course Progress
Section 5 of 1242% complete
Tutorials
Error Interface
Go handles errors as values, using the error interface for proper error handling.
Code Examples
Error Basicsgo
package main
import (
"fmt"
"errors"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}Custom Errorsgo
package main
import (
"fmt"
)
type ValidationError struct {
Field string
Message string
}
func (e ValidationError) Error() string {
return fmt.Sprintf("validation error on %s: %s", e.Field, e.Message)
}
func validateEmail(email string) error {
if email == "" {
return ValidationError{
Field: "email",
Message: "email cannot be empty",
}
}
return nil
}
func main() {
err := validateEmail("")
if err != nil {
fmt.Println(err)
}
}Exercises
Safe File Reader
Create a function that safely reads a file with proper error handling
INTERMEDIATEStarter Code:
package main
import (
"fmt"
"os"
)
func readFile(filename string) (string, error) {
// TODO: Implement safe file reading
return "", nil
}
func main() {
// TODO: Test with a file that exists and one that doesn't
}Hands-on Project
Configuration File Parser
Parse and validate a configuration file with comprehensive error handling
ADVANCED
Learning Objectives
- >Handle multiple error types
- >Validate data
- >Provide useful error messages
Project Tips
- > Start by understanding the requirements
- > Break the project into smaller tasks
- > Test your code frequently as you build
- > Add error handling throughout your code
- > Consider edge cases and validate inputs
- > Document your code with comments