引发异常
我想引发一个异常,因为它是用 Python 或 Java 编写的——以错误消息结束程序——。
错误消息可以返回到父函数:
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
}
但我希望它可以在发现错误时完成。下一篇会正确吗?
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)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按照惯例,Go 不会做这样的事情。它具有
恐慌
和恢复
,这有点类似于异常,但它们仅在非常特殊的情况下使用。找不到文件或类似情况根本不是特殊情况,而是一种非常常见的情况。特殊情况包括取消引用nil
指针或除以零。By convention, Go doesn't do things like this. It has
panic
andrecover
, 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 anil
pointer or dividing by zero.