What's the difference between panic("error_msg") and panic(error.New("error_msg")?

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

What's the difference between panic("error_msg") and panic(error.New("error_msg")?

问题

考虑到我正在使用原始的"go"错误包。

那么,panic(11)和panic("11")之间有什么区别?

英文:

Considering I'm using the original "errors" go package.

And, the difference between panic(11) and panic("11")?

答案1

得分: 5

panic 被定义为 func panic(v interface{}),调用 panic(anything) 会打印出 anything 的字符串表示,然后打印调用函数的堆栈跟踪。

唯一的区别是,如果你使用 recover,你将能够访问传递给 panic 的任何内容,例如:

func main() {
    defer func() {
        if err := recover(); err != nil {
            if n, ok := err.(int); ok && n == 11 {
                fmt.Println("got 11!")
            }
        }
    }()
    panic(11)
}
英文:

panic is defined as func panic(v interface{}), calling panic(anything) will print the the string representation of anything then the stacktrace of the calling function.

Only difference is, if you use recover, you will be able to access whatever you passed to panic, for example:

func main() {
	defer func() {
		if err := recover(); err != nil {
			if n, ok := err.(int); ok && n == 11 {
				fmt.Println("got 11!")
			}
		}
	}()
	panic(11)
}

答案2

得分: 3

panic("error_msg")panic("11") 会抛出一个字符串异常,而 panic(error.New("error_msg") 则会抛出一个错误异常,panic(11) 则会抛出一个整数异常。

如果你在 defer 中没有使用 recover 来处理这些异常,那么无论你使用哪种方式,都会打印出 "error_msg" 或 "11"。

英文:

panic("error_msg") and panic("11") panic a string while panic(error.New("error_msg") panics an error and panic(11) panics an integer.

If you do not handle these panics with recover during defer than it won't matter which you use, all will print the "error_msg" or "11".

huangapple
  • 本文由 发表于 2014年7月2日 20:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/24531422.html
匿名

发表评论

匿名网友

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

确定