Error Handling in Go
Go has a built-in error type, which is used to indicate an error condition. Functions that can return an error typically return a value of type error as their last return value.
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
result, err := divide(10.0, 2.0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
In this example, the divide() function returns an error if the second argument is zero. The caller of the function can check the error value to determine if an error occurred.
No comments:
Post a Comment