golang panic error recovery and simple usage scenarios

golang panic error recovery and simple usage scenarios

  • The sample code
package main

import(
    "fmt"
)

func main(){
    _,err:=deferPanic(8,0)
    if err!=nil{
        fmt.Println(err)
    }
    fmt.Println("这里还是会执行的")
}

//panic 回收测试
func deferPanic(x,y int)(z int,err error){
    //使用defer回收接收panic值
    defer func(){
        if e:=recover();e!=nil{
            err = e.(error)
            fmt.Println("看来deferPanic出错了",err)
        }
    }()
    z = x/y
    return
}
  • Note: deferPanic return to the design value. The return value inside the variable declaration, which are equivalent to a variable deferPanic and deferPanic returns the value of the variable value.
    • Reason: reduce the code definitions of the variables in the function
  • Execution order return, panic, defer the
    • panic to capture error messages
    • Implementation of return
    • defer recovery of the error message
  • application
    • For error is unknown. For example: an array of aspects, map

Guess you like

Origin www.cnblogs.com/MyUniverse/p/11526284.html