Lect18
.pdfПримерэквивалентности
#include <iostream> using namespace std;
int _tmain(int argc, _TCHAR* argv[]) try {
throw "Throwing char*";
}catch(void*) {
cout<< "Void* caught." << endl; cin.ignore();
return -1;
}catch(char*) {
cout << "Char* caught." << endl;
cin.ignore(); return -1;
}
return 0;
{
Результат:
Void* caught.
} |
21 |
|
Обработканепредвиденных исключений
Внекоторыхслучаяхбываетневозможно отследитьабсолютновсеслучаи выбрасываемыхисключений,нотребуется предсказуемоеповедениепрограммыпри этом.
Решитьпроблемуможетфункцияобработчик:
typedef void ( *terminate_function )( ); terminate_function set_terminate(
);terminate_function termFunction |
22 |
Примеробработки непредвиденныхисключений
#include <iostream> using namespace std;
void my_term() {
cout << "Караул, убивают!!!" << endl; cin.ignore();
exit(1);
}
int _tmain(int argc, _TCHAR* argv[]) set_terminate(my_term);
try {
throw "Throwing char*";
}catch(int) {
cout << "Int caught." << endl;
}
return 0;
{
Результат:
Караул,убивают!!!
} |
23 |
|
Стекиисключения.Пример1.
#include <iostream> using namespace std;
struct S { int s;
S(int ss): s(ss){
} cout << "Constructor for "<< s << endl;
S (const S& src) { s = src.s;
} cout << "Copy constructor for " << s << endl;
~S() {
};} cout << "Destructor of " << s << endl;
24
Стекиисключения.Пример1.
void FuncB(S obj) {
cout << "In FuncB: got" << obj.s << endl; } cout << "Exiting FuncB..." << endl;
void FuncA(S obj) {
cout << "In FuncA: got"<< obj.s << endl; obj.s = 22;
FuncB(obj);
} cout << "Exiting FuncA..." << endl;
int main() {
// Локальный объект
S mainObj = 11;
cout << "In main..." << endl; FuncA(mainObj);
cout << "Exiting main..." << endl; cin.ignore();
} return 0;
25
Стекиисключения.Пример1.
Результаты
Constructor for 11
In main...
Copy constructor for 11 In FuncA: got11
Copy constructor for 22 In FuncB: got22
Exiting FuncB...
Destructor of 22
Exiting FuncA...
Destructor of 22
Exiting main...
Destructor of 11
26
Стекиисключения.Пример2.
Модифицируемпример1:добавимвыбрасывание |
|
исключениявFuncB иперехватвmain |
|
… |
|
void FuncB(S obj) { |
|
cout << "In FuncB: got " << obj.s << endl; |
|
cout << "Throwing exception..." << endl; |
|
throw "Exception!"; |
|
cout << "Exiting FuncB..." << endl; |
|
} |
|
… |
|
int main() { |
|
// Локальный объект. |
|
S mainObj = 11; |
|
cout << "In main..." << endl; |
|
try { |
|
FuncA(mainObj); |
|
} catch(char* str) { |
|
cout << "Gaught in main: " << str << endl; |
|
} |
|
cout << "Exiting main..." << endl; |
|
cin.ignore(); |
|
return 0; |
|
} |
27 |
Стекиисключения.Пример2.
Результаты
Constructor for 11
In main...
Copy constructor for 11 In FuncA: got11
Copy constructor for 22 In FuncB: got 22 Throwing exception...
Destructor of 22
Destructor of 22
Gaught in main: Exception!
Exiting main...
Destructor of 11
28
Выбросисключенияв конструкторе
Привыбросеисключениявтеле конструктораиливспискеинициализации процессконструированияэкземпляра классапрерываетсяионсчитаетсяне созданным
◦Деструктордлятакогоклассавызваннебудет(!!!)
◦Будутвызваныдеструкторыдлятехполейкласса, длякоторыхуспеливыполнитьсяконструкторы
Порядоквызоваконструкторовполейклассасовпадаетс порядкомихперечисленияв объявлениикласса
Порядоквызовадеструкторов– обратныйпорядку вызоваконструкторов
29
Пример1
#include <stdlib.h> #include <iostream>
using namespace std;
void* operator new[](size_t size) { cout << "Global new[]." << endl; return malloc(size);
}
void operator delete[](void *p) {
}
cout << "Global delete[]." << endl; free (p) ;
30