Go Language Programming (ix) error handling

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

Error handling is an important topic to consider in any programming language.

Error interface

The go language introduces a standard pattern for error handling, the errors interface, which is defined as follows:

Typeerrorinterface{
  Error()string
}
for most functions, if you want to return an error, you can roughly define it as the following pattern, with error as the last of several return values, but this is not a mandatory requirement:

FuncFoo (paramint)(nint)  ,err error) {
    //
}
the code at the time of invocation recommends handling error conditions as follows:

n,err: =Foo(0)
Iferr! =null {
  //  error Handling
}Else{
  //Use return value n
}

below we use the actual code in the Go library to demonstrate how to use the custom error type.

First, define a type that is used to host the error message. Because of the flexibility of the interface in the go language, we do not need to inherit from the error interface or, like Java, need to use implements to explicitly specify the relationship between the type and interface, as follows:

Typepatherrorstruct{
  Opstring
  Pathstring
  Errerror
}
If so, how can the compiler know that Patherror can be passed as an error? The key is that the following code implements the error () method

Func(e*patherror)Error ( )   string{
    return e. Op  +   "      " + E.  Path  +   ":"   +  e. ERR. Error() 
}

Defer

Keyword defer is a very interesting feature of the Go language introduction.

Panic () and recover ()

The go language introduces two built-in functions panic () and recover () to report and handle run-time errors and error scenarios in the program



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.