Essential Go Panic and recover  Suggest an edit

Use cases for panic

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 function sqrt(n int) int that returns square root of a number.

Mathematically that only makes sense for n >= 0.

What should happen if the function is called with n < 0?

You can change the function to also return an error.

Or you could force program to crash, under the assumption that calling sqrt with negative n indicates a bug in the calling code and that bug should be fixed.

func sqrt(n int) int {
    if n < 0 {
        panic("sqrt only accepts n >= 0")
    }
    // ... calculate sqrt
}

Simplifying flow control in isolated piece of code

Sometimes it’s easier to propagate an error by panicking and recovering rather than returning errors.

This might be true e.g. in a parser.

When you use that technique, you should observe one rule: panic should not cross public API boundary.

In other words, if you implement a parser library, you should always recover all panics your code creates. Panic used for easier flow control should never reach the caller of your package API.

Protect a program from a crash in a goroutine

Unhandled panic in a goroutine crashes a program.

This is the right behavior most of the time (panic indicates a serious bug and you should fix bugs, not cover them up).

In rare occasions we don't want a single goroutine to bring down the whole program so we can wrap the code with a function that does recover at the top.

This technique is used in Go’s http server package which handles each connection in a separate goroutine. In a web server we don't want a rare bug in request handling code to crash the program.

  ↑ ↓ to navigate     ↵ to select     Esc to close