go exception handling panic / recover

go exception handling panic / recover

Go languages ​​currently (Go1.12) is no exception mechanism, but with panic / recover mode to handle errors. panic can lead to anywhere, but recover only valid defer the function call in

package main

import (
    "fmt"
)

func funcA() {
    fmt.Println("func A")
}

func funcB() {
    defer func() {
        err := recover()
        //如果程序出出现了panic错误,可以通过recover恢复过来
        if err != nil {
            fmt.Println("recover in B")
            fmt.Println(err)
        }
    }()
    panic("panic in B")
}

func funcC() {
    fmt.Println("func C")
}
func main() {
    funcA()
    funcB()
    funcC()
}
// func A
// recover in B
// panic in B
// func C

Guess you like

Origin www.cnblogs.com/guotianbao/p/12378694.html