Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- class BaseException
- {
- protected:
- string text;
- public:
- // чистая виртуальная функция, которая выводит текст исключения
- virtual string message() = 0;
- };
- class ArithmeticException :public BaseException // класс, который соответствует арифметическим операциям
- {
- public:
- // конструкторы класса
- ArithmeticException() // конструктор по умолчанию
- {
- text = "Error. Arithmetic Exception.";
- }
- ArithmeticException(string _text) { text = _text; } // конструктор с заданным текстом
- string message() { return text; } // переопределяем виртуальную функцию message()
- };
- class overflowException final :public ArithmeticException
- {
- public:
- overflowException() :ArithmeticException()
- {
- text = "Overflow exception.";
- }
- overflowException(string _text) :ArithmeticException(_text) //конструктор получает строку от пользователя
- { }
- string message()
- {
- return text;
- }
- };
- /* разновидность класса ArithmeticException - деление на 0,
- поскольку класс есть внизу иерархии и из него унаследовать ничего уже нельзя, то объявление класса содержит спецификатор final*/
- class DivideByZero final :public ArithmeticException
- {
- public:
- DivideByZero() :ArithmeticException() // конструктор, который содержит текст описывающий данное исключение
- {
- text = "Divide by zero.";
- }
- DivideByZero(string _text) :ArithmeticException(_text) // конструктор, который получает строку текста от пользователя
- { }
- string message()
- {
- return text;
- }
- };
- // разновидность класса BaseException
- // отрицательный индекс в массиве
- // это также final-класс
- class underflowException final :public BaseException
- {
- public:
- // конструктор получает аргумент по умолчанию
- underflowException(string _text = "Error. Negative Index.") { text = _text; }
- string message() { return text; }
- };
- // Демонстрационная функция для класса underflowException
- void DemoExceptions1()
- {
- cout << "проверка на граничное нижнее значение"<<endl;
- int* arr, size, b;
- cout << "enter size of array: ";
- cin >> size;
- arr = new int[size];
- for (int i = 0; i < size; i++)
- {
- cout << "arr[" << i << "] = ";
- cin >> arr[i];
- }
- int min = arr[0];
- for (int i = 1; i < size; i++)
- {
- if (arr[i] < min)
- {
- min = arr[i];
- }
- }
- cout << "enter an element: ";
- cin >> b;
- if (b < min)
- throw underflowException("Number is smallerr than we expected.");
- cout << b << " is bigger than " << min << endl;
- delete[] arr;
- };
- //Демонстрационная функция для класса overflowException
- void DemoException2()
- {
- cout << "проверка на граничное верхнее значение " << endl;
- int *arr, b;
- int size;
- cout << "Enter number of elements: ";
- cin>>size;
- arr = new int[size];
- for (int i = 0; i < size; i++)
- {
- cout << "arr[" << i << "] = ";
- cin >> arr[i];
- }
- int max = arr[0];
- for (int i = 1; i < size; i++)
- {
- if (arr[i] > max)
- {
- max = arr[i];
- }
- }
- cout << "Enter an element: ";
- cin >> b;
- if (b> max)
- throw overflowException("Number is bigger than we expected.");
- cout << b << " Is smaller than "<< max<<endl;
- delete[] arr;
- }
- // Демонстрационная функция для класса DivisionByZero
- void DemoExceptions3()
- {
- cout << "проверка на деление на 0" << endl;
- int a, b, c;
- cout << "a = "; cin >> a;
- cout << "b = "; cin >> b;
- if (b == 0) // делить на 0 запрещено
- throw DivideByZero("Divide by 0.");
- cout << "a / b = " << (double)a / b << endl;
- }
- void main()
- {
- setlocale(LC_ALL, "RUSSIAN");
- try
- {
- // вызвать функцию, генерирующую исключение
- DemoExceptions1(); // проверка на число меньше минимального
- DemoException2(); //проверка на число больше максимального
- DemoExceptions3(); // проверка на "Divide by 0"
- cout << "OK!" << endl;
- }
- catch (underflowException e)
- {
- cout << e.message() << endl; // обработать исключение
- }
- catch (DivideByZero e)
- {
- cout << e.message() << endl;
- }
- catch (overflowException e)
- {
- cout << e.message() << endl;
- }
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement