【问题标题】:Golang error handling: understanding panicGolang 错误处理:理解恐慌
【发布时间】:2015-03-29 08:50:22
【问题描述】:

我对 Go 还是很陌生,我正在尝试掌握 panic 函数。

到目前为止,我一直在使用这种类似的语法来处理程序中的错误:

func Find(i int) (item, error) {
  // some code

  if (not found) {
    return nil, errors.New('Not Found')
  }

  // if found:
  return myItem, nil

}

然后我偶然发现了panic 函数。我很难理解它。是否有可能摆脱 return 语句中的 error 并做这样的事情?

func Find(i int) item {
  // some code

  if (not found) {
    panic('Not found')
  }

  return myItem

}

如果是,调用函数时出现错误如何处理?

非常感谢

【问题讨论】:

标签: go


【解决方案1】:

您想使用recover 函数。

func Find(i int) item {
    defer func() {
        if e := recover(); e != nil {
            // e is the interface{} typed-value we passed to panic()
            fmt.Println("Whoops: ", e) // Prints "Whoops: Not Found"
        }
    }()

    if (not found)
    {    panic("Not Found")
    }

    return myItem
 }       

参考:http://blog.denevell.org/golang-panic-recover.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2021-07-23
    • 2017-05-07
    • 2018-10-28
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    相关资源
    最近更新 更多