gocrashrecoverpanic

Golang panic crash prevention


In Golang a panic without a recover will crash the process, so I end up putting the following code snippet at the beginning of every function:

defer func() {
    if err := recover(); err != nil {
        fmt.Println(err)
    }
}()

just in order to prevent my program from crashing. Now I'm wondering, is it really the way to go? Because I think it looks a little bit strange to put the same code everywhere.

It seems to me, the Java way, bubbling the exceptions up to the calling function, until the main function is a better way to control the exceptions/panics. I understand it's by Go's design, but what is the advantage of immediately crashing the process just like what Go does?


Solution

  • You should only recover from a panic if you know exactly why. A Go program will panic under essentially two circumstances:

    In the first case, a crash is appropriate because it means that your program has entered a bad state and shouldn't keep executing. In the second case, you should only recover from the panic if you expect it. The best way to explain this is simply to say that it's extremely rare, and you'll know that case if you see it. I'm almost positive that whatever code you're writing, you don't need to recover from panics.