引发一个异常

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

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语言不会像这样做。它有panicrecover,它们有点类似于异常,但它们只在非常特殊的情况下使用。找不到文件或类似的情况根本不是异常情况,而是非常常见的情况。异常情况包括解引用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.

huangapple
  • 本文由 发表于 2010年5月12日 20:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/2818884.html
匿名

发表评论

匿名网友

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

确定