Пример 1
#include <iostream>
using namespace std;
int main()
{ int num1, num2, var = 2;
while(var--)
{ cout << "Введите значение num1: ";
cin >> num1;
cout << "Введите значение num2: ";
cin >> num2;
cout << "num1 + num2 = " << num1 + num2 << endl;
cout << "num1 / num2 = ";
try //код, который может привести к ошибке
{ if (num2 == 0) throw 123;
cout << num1 / num2 << endl;
}
catch(int i)//сюда передастся число 123
{ cout << "Ошибка №" << i << " - на 0 делить нельзя!!!!" << endl;
}
cout << "num1 - num2 = " << num1 - num2 << endl;
cout << "=================================" << endl << endl;
}
return 0;
}
Пример 2
#include <iostream>
using namespace std;
Int main()
{ int num1, num2, var = 2;
while(var--)
{ cout << "Введите значение num1: ";
cin >> num1;
cout << "Введите значение num2: ";
cin >> num2;
cout << "num1 + num2 = " << num1 + num2 << endl;
cout << "num1 / num2 = ";
try
{ if (num2 == 0)
{ //генерировать символьную строку
throw "Ошибка - на 0 делить нельзя!!!!";
}
cout << num1 / num2 << endl;
}
catch(const char *str)//сюда передастся строка
{ cout << str << endl;
}
cout << "num1 - num2 = " << num1 - num2 << endl;
cout << "=================================" << endl << endl;
}
return 0;
}
Пример 3
#include <iostream>
using namespace std;
int division(int n1, int n2)
{ if (n2 == 0) throw 99;
return n1 / n2;
}
Int main()
{ int num1, num2, var = 2;
while(var--)
{ cout << "Введите значение num1: ";
cin >> num1;
cout << "Введите значение num2: ";
cin >> num2;
cout << "num1 + num2 = " << num1 + num2 << endl;
cout << "num1 / num2 = ";
try
{ cout << division(num1, num2);
cout << endl;
}
catch(int i)
{ cout << "Ошибка №" << i << " Деление на ноль." << endl;
}
cout << "num1 - num2 = " << num1 - num2 << endl;
cout << "=================================" << endl << endl;
}
return 0;
}
Пример 4
#include <iostream>
#include <cmath>
using namespace std;
class ErrorTriangle
{ public: double a,b,c; //параметры функции
string message; // сообщение
ErrorTriangle(double x, double y, double z, const string& s)
: a(x), b(y), c(z), message(s) {} // пустое тело
};
double Ha(double a, double b, double c)
{if ((a>0)&&(b>0)&&(c>0)) // если параметры правильные
{ if ((a+b>c)&&(a+c>b)&&(b+c>a)) // если треугольник
{ double p = (a+b+c)/2; // вычисляем высоту
return 2*sqrt(p*(p-a)*(p-b)*(p-c))/a;
}
else throw ErrorTriangle(a,b,c,"Heльзя построить треугольник со сторонами: ");
}
else throw ErrorTriangle(a,b,c,"Сторона треугольника должна быть больше 0: ");
}
Int main()
{ int a, b, c;
for(int i = 1; i<=3;i++)
{ cout << "Введите стороны треугольника:\n";
cout << "a = "; cin >> a;
cout << "b = "; cin >> b;
cout << "c = "; cin >> c;
try{
cout << "Высота, опущенная на сторону a = "<<Ha(a,b,c)<< endl;
}
catch(const ErrorTriangle& e) // обработка исключения
{ cout << e.message;
cout << e.a << ' ' << e.b << ' ' << e.c << endl;
}
}
return 0;
}
Пример 5
#include <iostream>
Int main()
{ const unsigned long size = 1000000000;
char* ptr;
try
{ ptr = new char[size];
// if (!ptr) throw std::bad_alloc();
}
catch (std::bad_alloc)
{ std::cout << "\n Исключение bad_alloc: невозможно разместить данные в памяти!\n";
return 1;
}
std::cout << "\n Память используется без сбоев.\n";
delete[] ptr;
return 0;
}
Пример 6
#include <iostream>
#include <cstring>
void withException( double a, double b ); // с исключениями
int returnErrorCode( double a, double b ); // возвращает код ошибки
void withSetErrorCode( double a, double b, int *err ); // устанавливает код ошибки
class myException : public std::exception
{ public:
myException( const char * errStr );
~myException() throw();
const char * what();
private:
char *errMesage;
};
myException::myException( const char *errStr )
{ if ( errStr != NULL )
{ const int ERRSTR_SIZE = strlen( errStr );
errMesage = new char[ ERRSTR_SIZE + 1 ];
strncpy( errMesage, errStr, ERRSTR_SIZE );
errMesage[ ERRSTR_SIZE ] = '\0';
} else
errMesage = NULL;
}
myException::~myException() throw()
{ if ( errMesage )
delete[] errMesage;
}
const char * myException::what()
{ if ( errMesage ) return errMesage;
else return "myException";
}