Arithmetic errors

Now we know how to design, check for, and handle recoverable errors in functions, but there's still errors hiding in the form of hardware limitations. Of course, you can't save an infinite amount of numbers in a finite amount of memory. Also, you want calculation to be fast, so that is an additional limitation. Floating point numbers do have a bit of error handling embedded in the most-used standard, but integers mostly just go into undefined behaviour when an overflow occurs.

For reasons of ergonomics (and performance), Rust actually doesn't differ from this behaviour by default. However, since undefined behaviour is about the worst that can happen for the correctness of your program, an integer overflow will crash it when compiled in debug mode. Undefined behaviour mostly means wrap-around in most cases, since that is how most hardware implementations work. But as you should never expect a specific thing to happen during undefined behaviour, Rust provides functions with explicit overflow behaviour for all integer types and all operations that can overflow in the specific case. Those are:

  • Checked methods that only return a value if overflow did not occur.
  • Overflowing methods that return the wrapped result and also a boolean value signaling if overflow occurred.
  • Saturating methods that clamp the result into the valid range.
  • Wrapped methods that explicitly wrap around, giving programmers a chance to mark it as wanted behaviour.