Error HandlingBeginner
1Question 1 of 1
goHow does explicit Error Handling work in Go and why are errors values?
Explanation & Concept
Go treats errors as ordinary values implementing the `error` interface (`Error() string`). Functions return error as an explicit secondary return value, and callers check `if err != nil`.
Go 1.13 introduced error wrapping (`fmt.Errorf("...: %w", err)`), `errors.Is()`, and `errors.As()` to inspect wrapped error hierarchies.
Code Example
go
package main
import (
"errors"
"fmt"
)
var ErrNotFound = errors.New("record not found")
func FindUser(id int) (string, error) {
if id != 100 {
return "", fmt.Errorf("lookup error for ID %d: %w", id, ErrNotFound)
}
return "Alex", nil
}
func main() {
user, err := FindUser(42)
if err != nil {
if errors.Is(err, ErrNotFound) {
fmt.Println("Handled missing user safely:", err)
return
}
fmt.Println("Unexpected error:", err)
return
}
fmt.Println("Found:", user)
}How It Works & Key Takeaways
Explicit error checking forces developers to address error branches directly at the call-site, avoiding unhandled exception crashes.
Mock Test · 1 Questions · Optional
Ready for Slices vs Arrays?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions