Error Handling in Go – Custom Errors, Panic, and Recover Guide
The error Type
Go handles errors explicitly as return values, rather than using exceptions.
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
}
Custom Errors
type NotFoundError struct {
Name string
}
func (e *NotFoundError) Error() string {
return e.Name + " not found"
}
panic and recover
panic stops normal execution immediately, while recover can catch a panic inside a deferred function to prevent the program from crashing.
func safeDivide(a, b int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from:", r)
}
}()
fmt.Println(a / b) // panics if b is 0
}
PreviousMastering Interfaces in Go – Polymorphism with Real Examples
Next Concurrency in Go – Goroutines and Sync.WaitGroup Tutorial
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)