英文:
Raise an exception
问题
我想要在程序中引发一个异常,就像在Python或Java中一样,以便以错误消息结束程序。
错误消息可以返回给父函数:
func readFile(filename string) (content string, err os.Error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return "", os.ErrorString("读取 " + filename + ": " + err)
}
return string(content), nil
}
但是我希望当发生错误时能够结束程序。下面的代码是否正确?
func readFile(filename string) (content string) {
content, err := ioutil.ReadFile(filename)
defer func() {
if err != nil {
panic(err)
}
}()
return string(content)
}
英文:
I would want to raise an exception as it's made in Python or Java --to finish the program with an error message--.
An error message could be returned to a parent function:
func readFile(filename string) (content string, err os.Error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return "", os.ErrorString("read " + filename + ": " + err)
}
return string(content), nil
}
but I want that it can be finished when the error is found. Would be correct the next one?
func readFile(filename string) (content string) {
content, err := ioutil.ReadFile(filename)
defer func() {
if err != nil {
panic(err)
}
}()
return string(content)
}
答案1
得分: 19
按照惯例,Go语言不会像这样做。它有panic
和recover
,它们有点类似于异常,但它们只在非常特殊的情况下使用。找不到文件或类似的情况根本不是异常情况,而是非常常见的情况。异常情况包括解引用nil
指针或除以零。
英文:
By convention, Go doesn't do things like this. It has panic
and recover
, which are sort of exception-like, but they're only used in really exceptional circumstances. Not finding a file or similar is not an exceptional circumstance at all, but a very regular one. Exceptional circumstances are things like dereferencing a nil
pointer or dividing by zero.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论