Golang panic crash prevention

前端 未结 2 1594
执念已碎
执念已碎 2021-01-17 17:37

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() {         


        
2条回答
  •  我在风中等你
    2021-01-17 18:19

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

    • A program logic error (such as a nil pointer dereference or out-of-bounds array or slice access)
    • An intentional panic (called using panic(...)) from either your code or code that your code calls

    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.

提交回复
热议问题