
Пример работы исключений
// пример обработки простого исключения
#include <iostream >
#include "myException.hpp"
#include <string >
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test << "\n";
if (test) throw test;
}
int main()
{
setlocale(LC_ALL,"Russian");
cout << "Start\n";
try { // начало блока try
cout << "Inside try block\n";
int i = 0;
if (i == 0) throw myException("Произ исключение 0 .... ");
if (i == 1) throw myException("Произ исключение 1 .... ");
if (i == 2) throw myException("Произ исключение 2 .... ");
Xtest(0);
Xtest(1);
Xtest(2);
//throw 10; // генерация ошибки
throw string("100"); // генерация ошибки
cout << "This will not execute";
}
catch (int i) { // перехват ошибки
cout << "Caught an exception -- value is: ";
cout << i << " \n";
}
catch (string e) { // перехват ошибки
cout << "Caught an exception -- value is: ";
cout << e << " \n";
}
catch (myException &e) { // перехват ошибки
cout << "Caught an exception -- value is: ";
cout << e.what() << " \n";
}
catch (...) { // перехват ошибки
cout << "Caught an exception\n";
}
cout << "End";
system("pause");
return 0;
}
/*
TODO:
http://www.c-cpp.ru/books/obrabotka-isklyucheniy
http://www.cyberforum.ru/cpp-beginners/thread579818.html
http://www.codenet.ru/progr/cpp/Try-Catch-Throw.php
http://it.kgsu.ru/C_STL/c_stl045.html
*/
/******************* class myException *******************/
#pragma once
#include <iostream>
#include <cstring>
#include <stdexcept >
using namespace std;
class myException :public exception
{
public:
myException( const char * errStr );
~myException() throw();
const char* what();
private:
char *errMesage;
};
/******************* class myException.cpp *******************/
#include <myException.hpp>
#include
//#define _CRT_SECURE_NO_WARNINGS
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";
}

