1 #include <stdexcept> 2 #include <iostream> 3 4 #include <boost/safe_numerics/safe_integer.hpp> 5 main(int,const char * [])6int main(int, const char *[]){ 7 // problem: cannot recover from arithmetic errors 8 std::cout << "example 7: "; 9 std::cout << "cannot recover from arithmetic errors" << std::endl; 10 std::cout << "Not using safe numerics" << std::endl; 11 12 try{ 13 int x = 1; 14 int y = 0; 15 // can't do this as it will crash the program with no 16 // opportunity for recovery - comment out for example 17 // std::cout << x / y; 18 std::cout << "error cannot be handled at runtime!" << std::endl; 19 } 20 catch(const std::exception &){ 21 std::cout << "error handled at runtime!" << std::endl; 22 } 23 // solution: replace int with safe<int> 24 std::cout << "Using safe numerics" << std::endl; 25 try{ 26 using namespace boost::safe_numerics; 27 const safe<int> x = 1; 28 const safe<int> y = 0; 29 std::cout << x / y; 30 std::cout << "error NOT detected!" << std::endl; 31 } 32 catch(const std::exception & e){ 33 std::cout << "error handled at runtime!" << e.what() << std::endl; 34 } 35 return 0; 36 } 37