英文:
How can I further my understanding of why Go handles errors the way it does?
问题
我已经谷歌了“Golang错误”,“Go错误处理”,“Go错误”和“Go错误详细”来看看其他人对这个主题的说法,也阅读了一些在线教程。
我还观看了像这样的YouTube视频:https://www.youtube.com/watch?v=Ph4eYD7Bgek
但是我仍然不明白为什么我在做任何事情之后都必须添加这些代码:
if err != nil {
fmt.Println(err)
}
为什么这不会自动发生呢?我仍然无法理解为什么这种方式比try-catch更好。我来自PHP背景,在PHP中,我几乎从不进行错误检查,每当出现问题时,它会自动记录一些东西,那么为什么我在Go中必须手动进行这些操作呢?有什么好处?我真的想要完全掌握这门语言,但是写重复的代码感觉太不对了。这违背了我对编程的理解,不要重复自己。
我该如何更好地理解这个问题?这种方式的原因和好处是什么?也许如果有人给出一些情况的例子,说明为什么这种错误处理方式是最好的方式,而不是try-catch,并且这种方式比根本不进行检查更好,就像我在PHP中所做的那样,我可能会理解得更清楚。
我已经阅读了Go的官方网站和其他各种在线教程,例如:
Oreilly的视频教程。
Pluralsight的视频教程。
英文:
I have Googled "Golang errors", "Go error handling", "Go errors" and "Go error verbose" to see what other people say on the subject, and also to read on some tutorials online.
I have also watched YouTube videos like these: https://www.youtube.com/watch?v=Ph4eYD7Bgek
But I still can not understand why I have to add these lines after everything I do:
if err != nil {
fmt.Println(err)
}
Why does this not happen automatically? And I still cannot understand why this way is better than try, catch. I come from a PHP background, and in PHP, I almost never did error checking, every time something went wrong it logged stuff automatically, so why do I have to this manually on Go? What are the benefits? I really want to "Go" 100% about learning this language, but it feels so wrong to write the same code over and over again. It goes against what I have learned about programming, to not repeat yourself.
How can I understand this more? What is the reason and benefits of this? Maybe I would understand if someone came with examples of some situations why this way of handling error is the best way, and not try catch, and this way is better than not checking at all, like I did in PHP.
And I have already read on the official website of Go. And various other tutorials online such as:
Video tutorial by Oreilly.
Video tutorial from Pluralsight.
答案1
得分: 1
我想把这个作为一个评论,但是有太多的链接:
返回一个带有上下文的“错误处理程序”函数的函数:
func ger(ctxt string) func(string, error) error {
return func(msg string, err error) error {
return fmt.Errorf("%s : %s : %v", ctxt, msg, err)
}
}
// 使用它:
er := ger("处理命令")
er("添加", err)
...列表还在继续,使用Google和SO搜索。
英文:
I wanted this to be a comment, but there are too many links:
Blog post: Error handling and Go
SO Question: Go — handling multiple errors elegantly?
SO Question: More terse error handling in Go
Code Review Question: A minimal version control system
Function that returns an "error handler" function with context:
func ger(ctxt string) func(string, error) error {
return func(msg string, err error) error {
return fmt.Errorf("%s : %s : %v", ctxt, msg, err)
}
}
// And using it:
er := ger("Handling cmd")
er("Add", err)
...the list goes on, use Google and SO search.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论