MyTetra Share
Делитесь знаниями!
исключения в перегрузке операторов, Исключения и наследование, Повторная генерация исключений, Функциональный try-блок
Время создания: 13.06.2020 20:15
Раздел: C++ - Примеры кода - Работа на уроке
Запись: Shut913/Tetra-notes-Programming/master/base/1592068542gicdi40lq6/text.html на raw.githubusercontent.com

#include <iostream>


// -- исключения в перегрузке операторов

//class MyArray;

//int& MyArray::operator[](const int index)

//{

// if (index < 0 || index >= getCount())

// throw -1;

//

// return _data[index];

//}

//class ArrayException

//{

//private:

// std::string _error;

//public:

// ArrayException(std::string error):

// _error{error} {}

//

// const char* getError() { return _error.c_str(); }

//};

//

//class ArrayInt

//{

//private:

// int _data[4];

//public:

// ArrayInt() {}

// int getCount() { return 4; }

// int& operator[](const int index)

// {

// if (index < 0 || index >= getCount())

// throw ArrayException("Invalid index");

//

// return _data[index];

// }

//};

//

//int main()

//{

// ArrayInt arr;

// try

// {

// int val = arr[7];

// }

// catch (ArrayException& e)

// {

// std::cout << "Error resived: " << e.getError() << "\n";

// }

//

// return 0;

//}


// -- Исключения и наследование

//class Parent

//{

//public:

// Parent() {}

//};

//

//class Child : public Parent

//{

//public:

// Child() {}

//};

//

//int main()

//{

// try

// {

// throw Child();

// }

// catch (Child& e)

// {

// std::cout << "Child exception\n";

// }

// catch (Parent& e)

// {

// std::cout << "Parent exception\n";

// }

//

// return 0;

//}


// std::exception

//int main()

//{

// try

// {

// std::string s;

// s.resize(-1);

// }

// catch (std::bad_alloc& e)

// {

//

// }

// catch (const std::exception& e)

// {

// std::cout << "Standard error: " << e.what() << "\n";

// }

//}

//

//int main()

//{

// try

// {

// throw std::runtime_error("Bad thing happened");

// }

// catch (const std::exception& e)

// {

// std::cout << "Standard error: " << e.what() << "\n";

// }

//

// return 0;

//}

//

//class ArrayException : public std::exception

//{

//private:

// std::string _error;

//public:

// ArrayException(std::string error): _error{error} {}

//

// const char* what() const

// {

// return _error.c_str();

// }

//};

//

//class ArrayInt

//{

//private:

// int _data[4];

//public:

// ArrayInt() {}

// int getCount() { return 4; }

// int& operator[](const int index)

// {

// if (index < 0 || index >= getCount())

// throw ArrayException("Invalid index");

//

// return _data[index];

// }

//};

//

//int main()

//{

// ArrayInt arr;

// try

// {

// int val = arr[7];

// }

// catch (ArrayException& e)

// {

// std::cout << "Error resived: " << e.what() << "\n";

// }

//

// return 0;

//}


//// Повторная генерация исключений

//class Database

//{

//public:

// Database() {}

//

// int getValue(std::string table, int id)

// {

// //...

// throw -1;

// }

//};

//

//int request(Database* d, std::string table, int id)

//{

// try

// {

// return d->getValue(table, id);

// }

// catch (int e)

// {

// std::cout << "Error was written to log-file: " << e << "\n";

//

// // throw "Database error"; // приемлемый

// // throw e; // не использовать

// throw; // правильно

// }

//}

//

//void main()

//{

// Database* d = new Database();

// try

// {

// request(d, "users", 234);

// }

// catch (int e)

// {

// std::cout << "catch in main()\n";

// }

//}


// Функциональный try-блок

//class A

//{

//private:

// int _x;

//public:

// A(int x) : _x{ x }

// {

// if (x <= 0)

// throw -1;

// }

//};

//

//class B : public A

//{

//public:

// B(int x)try : A(x)

// {

//

// }

// catch (...)

// {

// std::cout << "A constructor failed\n";

// }

//};

//

//int func(int a)try

//{

// //

//}

//catch (...)

//{

//

//}

//

//int main()

//{

// try

// {

// B b(0);

// }

// catch (int e)

// {

// std::cout << "Crash!\n";

// }

//}


// == Недостатки try/catch

// 1. Очиска памяти

//void main()

//{

// /*try

// {

// openFile(filename);

// writeToFile(content);

// closeFile();

// }

// catch (const std::exception& e)

// {

// closeFile();

//

// std::cout << "Failed write to file: " << e.what() << "\n";

// }*/

//

// /*class User {};

// void func(User u) {}

// void main()

// {

// User* user = new User();

//

// try

// {

// func(user);

//

// delete user;

// }

// catch (const UserException& e)

// {

// delete user;

//

// std::cout << "Failed user process" << e.what() << "\n";

// }

// }*/

//}

//

// 2. Исключения и деструктор (запрещено в деструкторах)

//

// 3. Проблема с производительностью

//

// Когда использовать try/catch (правила)

// 1. Ошибка возникает редко

// 2. Ошибка критическая

// 3. Ошибка не может быть обработана в том месте, где возникла

// 4. Нет альтернативного варианта


Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования