Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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

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

like image 913
Hewei Liu Avatar asked Jul 02 '14 12:07

Hewei Liu


2 Answers

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)
}
like image 159
OneOfOne Avatar answered Sep 22 '22 14:09

OneOfOne


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".

like image 39
Volker Avatar answered Sep 24 '22 14:09

Volker