英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论