Advertisement
palenda21

7laboop

Dec 16th, 2020
830
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class BaseException
  7. {
  8. protected:
  9.     string text;
  10.  
  11. public:
  12.     // чистая виртуальная функция, которая выводит текст исключения
  13.     virtual string message() = 0;
  14. };
  15.  
  16.  
  17. class ArithmeticException :public BaseException   // класс, который соответствует арифметическим операциям
  18. {
  19. public:
  20.     // конструкторы класса
  21.    
  22.     ArithmeticException()   // конструктор по умолчанию
  23.     {
  24.         text = "Error. Arithmetic Exception.";
  25.     }
  26.        
  27.     ArithmeticException(string _text) { text = _text; }  // конструктор с заданным текстом
  28.  
  29.    
  30.     string message() { return text; }   // переопределяем виртуальную функцию message()
  31. };
  32.  
  33. class overflowException final :public ArithmeticException
  34. {
  35. public:
  36.     overflowException() :ArithmeticException()
  37.     {
  38.         text = "Overflow exception.";
  39.     }
  40.     overflowException(string _text) :ArithmeticException(_text) //конструктор получает строку от пользователя
  41.     {    }
  42.  
  43.     string message()
  44.     {
  45.         return text;
  46.     }
  47.  
  48. };
  49.  
  50. /* разновидность класса ArithmeticException - деление на 0,
  51.    поскольку класс есть внизу иерархии и из него унаследовать ничего уже нельзя, то объявление класса содержит спецификатор final*/
  52.    
  53. class DivideByZero final :public ArithmeticException
  54. {
  55. public:
  56.         DivideByZero() :ArithmeticException()  // конструктор, который содержит текст описывающий данное исключение
  57.     {
  58.         text = "Divide by zero.";
  59.     }
  60.  
  61.    
  62.     DivideByZero(string _text) :ArithmeticException(_text)  // конструктор, который получает строку текста от пользователя
  63.     {    }
  64.  
  65.     string message()
  66.     {
  67.         return text;
  68.     }
  69. };
  70.  
  71. // разновидность класса BaseException
  72. // отрицательный индекс в массиве
  73. // это также final-класс
  74. class underflowException final :public BaseException
  75. {
  76. public:
  77.     // конструктор получает аргумент по умолчанию
  78.     underflowException(string _text = "Error. Negative Index.") { text = _text; }
  79.  
  80.         string message() { return text; }
  81. };
  82.  
  83. // Демонстрационная функция для класса underflowException
  84. void DemoExceptions1()
  85. {
  86.     cout << "проверка на граничное нижнее значение"<<endl;
  87.     int* arr, size, b;
  88.     cout << "enter size of array: ";
  89.     cin >> size;
  90.     arr = new int[size];
  91.     for (int i = 0; i < size; i++)
  92.     {
  93.         cout << "arr[" << i << "] = ";
  94.         cin >> arr[i];
  95.     }
  96.     int min = arr[0];
  97.     for (int i = 1; i < size; i++)
  98.     {
  99.         if (arr[i] < min)
  100.         {
  101.             min = arr[i];
  102.         }
  103.     }
  104.     cout << "enter an element: ";
  105.     cin >> b;
  106.     if (b < min)
  107.         throw underflowException("Number is smallerr than we expected.");
  108.  
  109.         cout << b << " is bigger than " << min << endl;
  110.        delete[] arr;
  111. };
  112.  
  113. //Демонстрационная функция для класса overflowException
  114. void DemoException2()
  115. {
  116.     cout << "проверка на граничное верхнее значение " << endl;
  117.     int *arr, b;
  118.     int size;
  119.     cout << "Enter number of elements: ";
  120.     cin>>size;
  121.     arr = new int[size];
  122.     for (int i = 0; i < size; i++)
  123.     {
  124.         cout << "arr[" << i << "] = ";
  125.         cin >> arr[i];
  126.     }
  127.     int max = arr[0];
  128.     for (int i = 1; i < size; i++)
  129.     {
  130.         if (arr[i] > max)
  131.         {
  132.             max = arr[i];
  133.         }
  134.     }
  135.     cout << "Enter an element: ";
  136.     cin >> b;
  137.     if (b> max)
  138.             throw overflowException("Number is bigger than we expected.");
  139.  
  140.         cout << b << " Is smaller than "<< max<<endl;
  141.         delete[] arr;
  142.        
  143. }
  144.  
  145.  
  146. // Демонстрационная функция для класса DivisionByZero
  147. void DemoExceptions3()
  148. {
  149.     cout << "проверка на деление на 0" << endl;
  150.     int a, b, c;
  151.     cout << "a = "; cin >> a;
  152.     cout << "b = "; cin >> b;
  153.     if (b == 0)  // делить на 0 запрещено
  154.         throw DivideByZero("Divide by 0.");
  155.     cout << "a / b = " << (double)a / b << endl;
  156. }
  157. void main()
  158. {
  159.     setlocale(LC_ALL, "RUSSIAN");
  160.     try
  161.     {
  162.         // вызвать функцию, генерирующую исключение
  163.         DemoExceptions1(); // проверка на число меньше минимального
  164.         DemoException2(); //проверка на число больше максимального
  165.         DemoExceptions3(); // проверка на "Divide by 0"
  166.         cout << "OK!" << endl;
  167.     }
  168.     catch (underflowException e)
  169.     {
  170.         cout << e.message() << endl;  // обработать исключение
  171.     }
  172.     catch (DivideByZero e)
  173.     {
  174.         cout << e.message() << endl;
  175.     }
  176.     catch (overflowException e)
  177.     {
  178.         cout << e.message() << endl;
  179.     }
  180.     return;
  181. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement