Go中的错误处理

huangapple go评论81阅读模式
英文:

Error Handling in Go

问题

我有一个像这样的Go代码,

main()
{
    做一些事情
    做一些事情
    .
    .
    .
    做一些事情
}

现在,我不知道哪个“做一些事情”抛出了错误。在Go中有没有办法捕捉错误并打印出来?如何做到?

英文:

I have a go code like this,

main()
{
    do something
    do something
    .
    .
    .
    do something
}

Now, I don't know which "do something" is throwing an error. Is it possible in Go to catch the error and print it? How?

答案1

得分: 2

你可能想要使用recover。或者,检查这些函数的返回值。在Go语言中,将错误值称为ok并立即检查它是惯用的做法。

meh, ok := do_something()
if !ok {
英文:

You probably want recover. Alternatively, check the return values from those functions. It's idiomatic in go to call the error value ok, and immediately check it.

meh, ok := do_something()
if !ok {

答案2

得分: 2

Go语言没有包含异常处理机制。然而,它有panic/recover机制,可以提供一点异常处理功能。

英文:

Go language did not include exception handling mechanism. However, it has panic/recover mechanism which gives a little bit of exception handling.

huangapple
  • 本文由 发表于 2011年12月2日 11:23:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/8351424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定