fork download
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. const int LIMIT = 100;
  5.  
  6. class safearray
  7. {
  8. public:
  9. void putel(int index, int value) { check_index(index); arr[index] = value;}
  10. int getel(int index) const { check_index(index); return arr[index];}
  11.  
  12. private:
  13. void check_index(int index) const
  14. {
  15. if (index < 0 || LIMIT <= index) {
  16. throw std::out_of_range("bad index " + std::to_string(index) + " for safearray");
  17. }
  18. }
  19. private:
  20. int arr[LIMIT];
  21. };
  22.  
  23. int main() {
  24. safearray a;
  25. const int value = 23456;
  26.  
  27. for (int index : {7, -1, 101}) {
  28. try {
  29. a.putel(index, value);
  30. std::cout << "value at " << index << " is " << a.getel(index) << std::endl;
  31. } catch (const std::exception& e) {
  32. std::cout << "Error:" << e.what() << std::endl;
  33. }
  34. }
  35. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
value at 7 is 23456
Error:bad index -1 for safearray
Error:bad index 101 for safearray