How to return a value in a Go function that panics?

后端 未结 2 1287
天命终不由人
天命终不由人 2020-11-28 13:49

My Go function is expected to return a value, but it may panic when calling a library function. I can use recover() to capture this in a deferred call, but how

2条回答
  •  独厮守ぢ
    2020-11-28 14:17

    Using the example in icza's answer, and if you wonder what happens if you recover from the panic but don't assign the value for the named return, like this:

    func main() {
        fmt.Println("Returned:", MyFunc()) // false
    }
    
    func MyFunc() (ret bool) {
        defer func() {
            if r := recover(); r != nil {
            }
        }()
        panic("test")
        return true
    }
    

    The function will return the zero value of the specified return type.

    Run the example in the Go Playground

提交回复
热议问题