Обработка исключительных ситуаций
.pdfПример
#include <iostream> |
|
void f2(){ |
|
|
|
#include <fstream> |
|
try{ f3(); } |
|
|
|
using namespace std; |
|
catch(except& e){ |
|
|
|
class except{ |
|
cout<<"Exception caught in f2 and |
|
rethrow"<< endl; |
|
public: |
|
|
|
throw e;} } |
|
except(){ |
|
|
|
void f1(){ |
|
cout<<"Exception |
|
|
|
try{f2(); } |
|
constructed"<<endl; } |
|
|
|
|
|
except(const except&){ |
|
catch(except& e) |
|
|
|
cout<<"Exception copied"<<endl; |
} |
{ |
|
||
void check(){ |
|
cout<<"Exception caught in f1"<<endl; |
|
|
|
cout<<"Exception |
|
e.check();} } |
checked"<<endl;} |
|
int _tmain() |
}; |
|
{ |
void f3(){ throw except();} |
|
f1(); |
|
|
cin.get(); |
|
|
return 0; |
|
|
} |
Обработка исключений ,
сгенерированных оператором
new
#include <new> #include <iostream> using namespace std; int _tmain()
{
int *p,i; try{
p=new int[32];
}
catch(bad_alloc){ cout<<"Allocation falure.\n"; return 1;
}
for(i=0;i<32;i++) { p[i]=i; cout<<p[i]<<" ";} delete [] p;
return 0;
}
Перегрузка new и delete
void* operator new(size_t size)
{
return pointer_to_mem;
}
void* operator new[](size_t size)
{
return pointer_to_mem;
}
void operator delete(void *p){
}
void operator delete[](void *p){
}
Пример
class three_d{ int x,y,z; public:
three_d(){x=y=z=0;} three_d(int i, int j, int k){ x=i;y=j;z=k;}
void* operator new(size_t size); void* operator new[](size_t size); void operator delete(void *p); void operator delete[](void *p);
void show(){cout<<x<<y<<z<<endl;}
};
void* three_d::operator new(size_t size){
void *p; p=malloc(size); if(!p){ bad_alloc ba; throw ba;
}
}
void three_d::operator delete(void *p){ free(p);
}
Пример
void* three_d::operator new[](size_t size){
void *p; p=malloc(size); if(!p){ bad_alloc ba; throw ba;
}
}
void three_d::operator delete[](void *p){
free(p);
}
int main()
{
three_d *p1; int i;
try{
p1=new three_d[32];
}
catch(bad_alloc){ cout<<"Allocation falure.\n"; return 1;
}
for(i=0;i<32;i++) p1[i].show(); delete [] p1;
return 0;
}
Стандартные функции
void exit(int status);
status=0//EXIT_SUCCESS status=1//EXIT_FALURE
void abort();