$Id: 135

$SOId: rd6000v3

Using of panic in Go should be extremely rare but it does have valid use cases.

Force crash on bad API usage

This is similar to using assert in other languages.

Imagine you're writing a httpGet function that downloads content of the URL.

What should happen when URL is empty string? It's obviously a mistake on the part of the caller.

You can return an error but you can also for a crash with panic:

func httpGet(uri string) ([]byte, error) {
    if uri == "" {
        panic("uri cannot be empty")
    }
    // ... download the url
}

Sometimes it's better because an error can be ignored or the program might assume that it's a valid error condition, like a website being down.

Forcing a crash increases chances that the developer will look at the problem and fix it.

If you do it often, this helper function will be useful:

func panicIf(cond bool, args ...interface{}) {
	if !cond {
		return
	}
	if len(args) == 0 {
		panic(errors.New("cond failed"))
	}
	format := args[0].(string)
	args = args[1:]
	err := fmt.Errorf(format, args)
	panic(err)
}

Now this can be written as a single line:

func httpGet(uri string) ([]byte, error) {
    panicIf(uri == "", "uri cannot be empty")
    // ... download the url
}

Function panicIf is flexible. You can call it as: