Error Handling in Go
Go uses a simple, explicit approach to error handling using the built-in error
type.
import "errors"
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
This approach encourages checking for and handling errors explicitly.