I made a quick search but could not find any documented policy on when it is appropriate for a function (in
std or elsewhere) to panic. Is there such a policy? If not, should one be written?
This issue recently came up in another thread here: Duration as milliseconds.
I was astounded to see such broad support among the responders for
std::time::Duration::as_millis() to panic. I’ve always regarded panicking as a last resort, when there’s no other way out. The natural solutions for
as_millis would of course be to return a bigger type or a
Result. Any given input, as a validly constructed
Duration, is also an expected value, and a valid one.
Are there other places in
std or in other officially hosted or supported libraries where the question of panicking or not need to be discussed or determined?
Towards a policy
I’m going to jot down a few ideas that come to mind. Please help out in specifying a proper policy:
A valid input to a
fnshould not, in it self, be an acceptable cause for panicking. Now you may ask, what exactly is meant by “valid”, and that’s a fair objection that needs some examination.
fnmay only panic when there’s no other reasonable way to deal with the task, or recover from a failure.
If a non-panicking
fncan reasonably be designed then that is a good first-hand choice. Panicking behaviour does not draw upon the strengths of the type system. In fact, it’s kind of a cop out in many cases and should not be encouraged.
Even though panicking is an efficient, and easy-to-use means of contract enforcement it should not be used as an excuse to not choose the proper contract. Perhaps it’s easier to just
Durationcannot fit inside a
u64, and most of the time it would fit, but that’s a bad reason. The semantics of the values represented is more important than some easy-to-conceive use cases.