Go language Development (vii), GO language error handling

Source: Internet
Author: User
Tags sprintf

Go language Development (vii), GO language error handling one, defer delay function 1, defer delay function introduction

Defer is not executed immediately at the time of Declaration, but after the function return, followed by the Filo (advanced out) principle of each defer, typically used for exception handling, freeing up resources, cleaning up data, logging, and so on.
Each time the defer statement executes, the return value and parameter values of the defer decorated function are evaluated and saved as usual, but the defer decorated function does not execute. Until the previous function returns, all defer functions are executed in reverse order of the defer declaration. Any return value of the function that defer modifies is discarded.
If the value of a defer-modified function is nil, the defer function panic (exception) when the function executes, not panic when the defer statement executes. The upper-level function of the defer function, even if it throws an exception, is executed by the defer modifier, ensuring that the resource is legitimately freed.
Examples of use of the defer delay function are:

package mainimport "fmt"func deferTest(){   defer fmt.Println(1)   defer fmt.Println(2)   fmt.Println(3)}func main() {   deferTest()//3,2,1}
2. Defer delay function application

A. Simplify Resource Recovery

mu.Lock() defer mu.Unlock()

Defer? Have a certain overhead, in order to save performance can avoid the use of defer?
B. Capturing panic anomalies
In the go language, panic is used to throw exceptions, and recover is used to catch exceptions.
Recover can only be used in defer statements, calling recover directly is not valid.

package mainimport "fmt"func deferRecover(){   defer func () {      if r := recover(); r != nil {         fmt.Println("recover")      }   }()   fmt.Println("exception will be happen")   panic("exception has happped.")   fmt.Println("return normally")}func main() {   deferRecover()}

C, modify the return value
Defer can be used to modify the return value of a function after the return.

package mainimport "fmt"func deferReturn(a,b int)(sum int){   defer func(){      sum += 100   }()   sum = a + b   return sum}func main() {   sum := deferReturn(1,6)   fmt.Println(sum)//107}

D. Safe Recovery of resources

func set(mu *sync.Mutex, arr []int, i, v int) {   mu.Lock()   defer mu.Unlock()   arr[i] = v}

If the runtime throws a slice out-of-bounds exception, you can guarantee mu. Unlock () is called.

Second, error handling 1, error handling Introduction

The go language provides a simple error handling mechanism through the built-in error interface.
The error type is an interface type and is defined as follows:

type error interface {    Error() string}

The error interface type is introduced in Golang as the standard mode for fault handling, and if the function returns an error, the return value type list must contain error.

2, error handling use
package mainimport (   "fmt"   "errors")//定义一个DivideError类型type DivideError struct {   dividee int   divider int}//实现error接口func (err *DivideError) Error() error{   strFormat := `Cannot proceed, the divider is zero.dividee: %d divider: 0`   return errors.New(fmt.Sprintf(strFormat, err.dividee))}//定义除法运算func divide(vardividee int, vardivider int)(result int, errmsg error){   if vardivider == 0{      divideErr := DivideError{         dividee:vardividee,         divider:vardivider,      }      errmsg = divideErr.Error()      return 0,errmsg   }else{      return vardividee/vardivider,nil   }}func main() {   //正常情况   if result, err := divide(100, 10); err != nil{      fmt.Println(err)   }else{      fmt.Println("100/10 = ", result)   }   //当被除数为零的时候会返回错误信息   if _, errorMsg := divide(100, 0); errorMsg != nil{      fmt.Println(errorMsg)   }}
Three, exception handling 1, exception handling introduction

Go uses the panic () function to throw an exception and call the Recover () function in the defer statement to catch the exception.

func panic(interface{})//接受任意类型参数 无返回值 func recover() interface{}//可以返回任意类型 无参数

Panic () is a built-in function that interrupts the original control flow and enters a panic process. When function f calls panic, the execution of the function f is interrupted, but the delay function in F (which must be the loaded defer before panic) executes normally, and the F function returns from layer to row until all the called functions in goroutine of panic occur, and the program exits. Exceptions can be directly called panic or generated by a run-time error, such as an array of accesses that are out of bounds.
Recover () is a built-in function that allows goroutine to be restored to the panic process. The recover is only valid in the delay function. During normal execution, the call to recover returns nil and has no other effect. If the current goroutine is caught in panic, the call recover can capture the input value of panic and resume normal execution.
In general, recover () should be executed in a function that uses the DEFER keyword to effectively intercept the error-handling process. If the recovery procedure is not explicitly called in the Goroutine where the exception occurred (using the Recover keyword), it causes the process that goroutine belongs to print the exception information and exits directly.

2. Exception Handling Use example
package mainimport (   "errors"   "fmt")//定义一个DivideError类型type DivideError struct {   dividee int   divider int}//实现error接口func (err *DivideError) Error() error{   strFormat := `Cannot proceed, the divider is zero.dividee: %d divider: 0`   return errors.New(fmt.Sprintf(strFormat, err.dividee))}//定义除法运算func divide(dividee int, divider int)(result int){   defer func() {      if r := recover();r != nil{         divideErr := DivideError{            dividee:dividee,            divider:divider,         }         fmt.Println(divideErr.Error())      }   }()   result = dividee/divider   return result}func main() {   a := divide(100,0)   fmt.Println(a)}

Go language Development (vii), GO language error handling

Related Article

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.