61 lines
1.0 KiB
Go
61 lines
1.0 KiB
Go
|
package errors
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
var ErrDivisionByZero = errors.New("cannot divide by zero")
|
||
|
|
||
|
func divide(a, b float64) (float64, error) {
|
||
|
if b == 0 {
|
||
|
return -1, ErrDivisionByZero
|
||
|
}
|
||
|
|
||
|
return a / b, nil
|
||
|
}
|
||
|
|
||
|
func isMultipleOf(a, b float64) (bool, error) {
|
||
|
for {
|
||
|
if a == 1 {
|
||
|
return true, nil
|
||
|
}
|
||
|
|
||
|
if a < 1 {
|
||
|
return false, nil
|
||
|
}
|
||
|
|
||
|
if val, err := divide(a, b); err != nil {
|
||
|
return false, fmt.Errorf("error during divide() op: %w", err)
|
||
|
} else {
|
||
|
a = val
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return false, nil
|
||
|
}
|
||
|
|
||
|
func Errors() {
|
||
|
if val, err := divide(1, 0); err != nil {
|
||
|
fmt.Printf("Got error: %v\n", err)
|
||
|
} else {
|
||
|
fmt.Printf("1 / 0 = %f\n", val)
|
||
|
}
|
||
|
|
||
|
if _, err := isMultipleOf(6, 2); err != nil {
|
||
|
fmt.Printf("Got error: %v\n", err)
|
||
|
} else {
|
||
|
fmt.Printf("6 is a multiple of 2\n")
|
||
|
}
|
||
|
|
||
|
if _, err := isMultipleOf(6, 0); err != nil {
|
||
|
fmt.Printf("Got error: %v\n", err)
|
||
|
|
||
|
if errors.Is(err, ErrDivisionByZero) {
|
||
|
fmt.Printf("We encountered a division by zero error!\n")
|
||
|
}
|
||
|
} else {
|
||
|
fmt.Printf("6 is a multiple of 0\n")
|
||
|
}
|
||
|
}
|