Add errors
This commit is contained in:
parent
4bc7680ff7
commit
d3e9911fe5
60
errors/errors.go
Normal file
60
errors/errors.go
Normal file
@ -0,0 +1,60 @@
|
||||
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")
|
||||
}
|
||||
}
|
6
main.go
6
main.go
@ -2,10 +2,12 @@ package main
|
||||
|
||||
// import "git.sangeeth.dev/gobyexample/runes"
|
||||
// import "git.sangeeth.dev/gobyexample/structs"
|
||||
import "git.sangeeth.dev/gobyexample/generics"
|
||||
// import "git.sangeeth.dev/gobyexample/generics"
|
||||
import "git.sangeeth.dev/gobyexample/errors"
|
||||
|
||||
func main() {
|
||||
// runes.Runes()
|
||||
// structs.Structs()
|
||||
generics.Generics()
|
||||
// generics.Generics()
|
||||
errors.Errors()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user