++ . . , new . new , , , . , , , , , , .
? -, ++ , return, . , -, . , , , , . , , , . , , , () .
, (), . , , . .
try {... } , .
catch (1 _) {... } [
catch (2 _) {... }... ]
; (.. ) . , . . -. , ( ++) .
++ , . : catch () {... }
t hrow ( ); . , . ( class struct) .
|
|
.
exception . : exception( ) what(), .
class exception{ // base of all library exceptions
public:
explicit exception(const char *_Message = "unknown"):_Ptr(_Message) {}
virtual const char * what() const
{ // return pointer to message string
return (_Ptr!= 0? _Ptr: "unknown exception");
}
protected: const char *_Ptr;
};
, .
, new ( , , - ) bad_alloc. , , , , , .
#include "stdafx.h"
#include <new>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int i = 0;
int *p;
try{// ( )
while (1) {cerr<<"\n i= "<<i++; p = new int[10000000];cerr<<hex<<p;}
}
catch(std::bad_alloc x) {
cerr<<"\n Processing of exception = "<<x.what();
}
cerr<<"\nEnd\n";
return 0;
}
, . , - , new bad_alloc, .
.
#include "stdafx.h"
#include <new>
#include <iostream>
class except{//1 , .
int CodError; //2
public: //3
except(int i){CodError = i;} //4
virtual int what(){return CodError;} //5
}; //6
void f1(int i){ //7
cout<<"\nf1()"; //8
if(i==1)throw except(i); //9
}//10
void f2(int i){ //11
cout<<"\nf2()"; //12
f1(i); //13
}//14
int main(int argc, char* argv[]) //15
{ //16
try{//17 ,
f2(0); //18
f2(1); //19
f2(0); //20
} //21
catch(except x){//22
cout<<"\n processing except x.CodError = "<<x.what(); //23
} //24
}
except ( 16), . , , , . , , .
|
|
f1() 9 throw except(i) except.
main 17 21 , try, , , , , .
6