Add errors

This commit is contained in:
Sangeeth Sudheer 2024-04-27 15:06:29 +05:30
parent 4bc7680ff7
commit d3e9911fe5
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 64 additions and 2 deletions

60
errors/errors.go Normal file
View 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")
}
}

View File

@ -2,10 +2,12 @@ package main
// import "git.sangeeth.dev/gobyexample/runes" // import "git.sangeeth.dev/gobyexample/runes"
// import "git.sangeeth.dev/gobyexample/structs" // 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() { func main() {
// runes.Runes() // runes.Runes()
// structs.Structs() // structs.Structs()
generics.Generics() // generics.Generics()
errors.Errors()
} }