Handling Errors in Go
Explore error handling in Go with a function that divides numbers, demonstrating how to create and handle custom errors.
Explore error handling in Go with a function that divides numbers, demonstrating how to create and handle custom errors.
package main
import (
"fmt"
"errors"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero is not allowed")
}
return a / b, nil
}
func main() {
result, err := divide(10.0, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}