Go language Error

Source: Internet
Author: User
The go language introduces a standard model for error handling, the error interface, which is defined as follows:
Type Error Interface {
Error () string
}
For most functions, if you want to return an error, you can generally define it as the following pattern, which returns the error as a variety of
The last of the values, but this is not a mandatory requirement:
Func Foo (param int) (n int, err error) {
// ...
}
The code at the time of the call suggests that the error condition be handled as follows:
N, Err: = Foo (0)
If Err!= nil {
Error handling
} else {
Use return value n

} Custom Error

Package main

Import (
	"FMT"
	"Time"
)
//Define an error structure body to load error message
type myerror struct {
	when Time. Time
	What string
}
//Implementation Error Interface Error () method
func (e *myerror) error () string {return
	FMT. Sprintf ("At%v,%s",
		E.when, E.what)
}
//Defines a method, note that the return value type contains an error
func run () error {
	returns &myerror{time
		. Now (),
		"It didn ' t work",
	}

func main () {
	If err: = run (); Err!= Nil {
		//because the run () method returns an ER Ror the value of the Err parameter is the return value of the error () method and a string string
		fmt. PRINTLN (Err)
	}
}


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.