Go Language exercise:errors

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Copy your Sqrt function from the earlier exercises and modify it to return an error value.

SqrtShould return a Non-nil error value when given a negative number, as it doesn ' t support complex numbers.

Create a new type

Type errnegativesqrt float64

and make it error a by giving it a

Func (e errnegativesqrt) Error () string

Method such that ErrNegativeSqrt(-2).Error() returns "cannot Sqrt negative number: -2" .

Note: a call to inside the method would send the program into an fmt.Print(e) Error infinite loop. You can avoid this by converting first e : fmt.Print(float64(e)) . Why?

Change your Sqrt function to return the ErrNegativeSqrt value when given a negative number.

Package Main

Import (
"FMT"
)

Type errnegativesqrt float64

Func (e errnegativesqrt) Error () string{
Return to FMT. Sprintf ("Cantnot Sqrt negative Number:%v", Float64 (e))
}

Func Sqrt (f float64) (Float64, error) {
If f < 0 {
return 0, errnegativesqrt (f)
}
Z: = f
For I: = 0; I < 10; i++ {
z = (z + f/z)/2
}
Return Z, Nil
}

Func Main () {
If value, err: = Sqrt (-2); Err! = Nil {
Fmt. PRINTLN (ERR)
} else {
Fmt. Println (value)
}
If value, err: = Sqrt (2); Err! = Nil {
Fmt. PRINTLN (ERR)
} else {
Fmt. Println (value)
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.