异常学习

#include < exception >
#include
< iostream >
using namespace std;

void terminator() ... {
cout
<<"I'llbeback!"<<endl;
exit(
0);
}


void ( * old_terminate)() = set_terminate(terminator);

class Botch ... {
public:
classFruit...{};
voidf()...{
cout
<<"Botch::f()"<<endl;
throwFruit();
}

~Botch()...{throw'c';}
}
;

int main() ... {
try...{
Botchb;
b.f();
}
catch(...)...{
cout
<<"insidecatch(...)"<<endl;
}

}
/**/ ///:~
没catch的异常可以用set_terminate来处理。同时,可以看出在析构函数里抛异常是很郁闷的一件事情。


如果在生成对象时候产生异常,会自己析购已经生成的,而产生异常的那一次生成,没有调用析构函数。
// :C01:Cleanup.cpp
// Exceptionscleanupcompleteobjectsonly.
#include < iostream >
using namespace std;

class Trace ... {
staticintcounter;
intobjid;
public:
Trace()
...{
objid
=counter++;
cout
<<"constructingTrace#"<<objid<<endl;
if(objid==3)throw3;
}

~Trace()...{
cout
<<"destructingTrace#"<<objid<<endl;
}

}
;

int Trace::counter = 0 ;

int main() ... {
try...{
Tracen1;
//Throwsexception:
Tracearray[5];
Tracen2;
//Won'tgethere.
}
catch(inti)...{
cout
<<"caught"<<i<<endl;
}

}
/**/ ///:~

你可能感兴趣的:(C++,c,F#,C#)