...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Safe Numerics |
The exception policy specifies what is to occur when a safe operation cannot return a valid result. A type is an ExceptionPolicy if it has functions for handling exceptional events that occur in the course of safe numeric operations.
EP |
A type that fulfills the requirements of an ExceptionPolicy |
e | A code from safe_numerics_error
|
message | A const char * which refers to a text message about the cause of an exception |
Whenever an operation yield an invalid result, one of the following functions will be invoked.
Expression | Return Value | Invoked when: |
---|---|---|
EP::on_arithmetic_error(e, message) |
void | The operation cannot produce valid arithmetic result such as overflows, divide by zero, etc. |
EP::on_undefined_behavior(e,
message) |
void | The result is undefined by the C++ standard |
EP::on_implementation_defined_behavior(e,
message) |
void | The result depends upon implementation defined behavior according to the C++ standard |
EP::on_uninitialized_value(e,
message) |
void | A variable is not initialized |
This function is used to invoke the exception handling policy for a particular exception code.
template<class EP> constexpr void dispatch<EP>(const boost::numeric::safe_numerics_error & e, char const * const & msg);
The library header <boost/safe_numerics/exception_policies.hpp>
contains a number of pre-made exception policies:
boost::numeric::loose_exception_policy
Throw on arithmetic errors, ignore other errors. Some applications ignore these issues and still work and we don't want to update them.
boost::numeric::loose_trap_policy
Same as above in that it doesn't check for various undefined behaviors but traps at compile time for hard arithmetic errors. This policy would be suitable for older embedded systems which depend on bit manipulation operations to work.
boost::numeric::strict_exception_policy
Permit just about anything, throw at runtime on any kind of error. Recommended for new code. Check everything at compile time if possible and runtime if necessary. Trap or Throw as appropriate. Should guarantee code to be portable across architectures.
boost::numeric::strict_trap_policy
Same as above but requires code to be written in such a way as to make it impossible for errors to occur. This naturally will require extra coding effort but might be justified for embedded and/or safety critical systems.
boost::numeric::default_exception_policy
Alias for strict_exception_policy
, One would use
this first. After experimentation, one might switch to one of the
above policies or perhaps use a custom policy.