example13.cpp 1.1 KB

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