Go语言内建方法之panic&&recover

  • 处理异常

    • panic 抛出异常
    • recover 捕获异常
    package main
    import (
        "fmt"
    )
    func main() {
        recoverPanic()
    }
    func recoverPanic()  {
        defer coverPanic()                  //捕获异常
        //panic("panic")                    //panic message panic
        //panic(errors.New("error"))        //error message error
        panic(1)                          //unknown panic 1
    }
    func coverPanic()  {
        message := recover()
        switch message.(type) {
        case string:
            fmt.Println("panic message",message)
        case error:
            fmt.Println("error message",message)
        default:
            fmt.Println("unknown panic",message)
        }
    }

关注友儿不迷路

Last modification:September 23rd, 2020 at 09:37 am
如果觉得我的文章对你有用,请随意赞赏