Dealing with panics
In general, a panic is an unrecoverable situation, such as resource exhaustion or a violation of an invariant (that is, a bug). Some panics, such as out of memory or divide by zero, will be raised by the runtime (or raised by the hardware and transferred to the program as a panic). You should generate a panic in your program when you detect a bug. But how do you decide if a situation is a bug and you should panic or an error?
In general, an external input (user input, data submitted by an API, or data read from a file) should not cause a panic. Such situations should be detected and returned as meaningful errors to the user. A panic in this situation would be, for instance, a failed compilation of a regular expression that is declared as a constant string in your program. The input is not something that can be fixed by re-running the program with different inputs; it is simply a bug.
If a panic is not handled with recover
, the program will terminate by printing...