1
\$\begingroup\$

New to Go, trying to solve Tour of Go, Exercise 56, which is about error handling.

Can the following error handling method can be further improved?

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(f float64) (float64, error) {
    if f > 0 {
        return math.Sqrt(f), nil
    } else {
        return 0, ErrNegativeSqrt(f)
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}
\$\endgroup\$
1
  • \$\begingroup\$ Minor point, but you don't need to wrap the return 0, ErrNegativeSqrt(f) in an else block. The go vet tool would complain about this. \$\endgroup\$
    – rxmnnxfpvg
    Commented Dec 8, 2013 at 8:29

2 Answers 2

1
\$\begingroup\$

I would name the error ErrSqrtNegative instead of ErrNegativeSqrt.

Sqrt(0) should not be an error.

In case of error, I would use math.NaN(), ErrSqrtNegative(f) as the return values.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Hmm. It looks like the exercise calls for the error to be named ErrNegativeSqrt. \$\endgroup\$ Commented Oct 23, 2013 at 5:34
0
\$\begingroup\$

For example,

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %g", e)
}

func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, ErrNegativeSqrt(f)
    }
    const delta = 1e-12
    z := f
    for {
        zz := z
        z -= (z*z - f) / (2 * z)
        if math.Abs(z-zz) < delta {
            break
        }
    }
    return z, nil
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}

Output:

1.414213562373095 <nil>
0 cannot Sqrt negative number: -2
\$\endgroup\$
1
  • \$\begingroup\$ Code-only answers do not constitute a review. Please explain how your changes improve the original code. \$\endgroup\$ Commented Jan 28, 2014 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.