#include
<
exception
>
#include < iostream >
using namespace std;
void terminator() {
cout << "I'll be back!" << endl;
exit(0);
}
void ( * old_terminate)() = set_terminate(terminator);
class Botch {
public:
class Fruit {};
void f() {
cout << "Botch::f()" << endl;
throw Fruit();
}
~Botch() { throw 'c'; }
} ;
int main() {
try {
Botch b;
b.f();
} catch(...) {
cout << "inside catch(...)" << endl;
}
} ///:~
#include < iostream >
using namespace std;
void terminator() {
cout << "I'll be back!" << endl;
exit(0);
}
void ( * old_terminate)() = set_terminate(terminator);
class Botch {
public:
class Fruit {};
void f() {
cout << "Botch::f()" << endl;
throw Fruit();
}
~Botch() { throw 'c'; }
} ;
int main() {
try {
Botch b;
b.f();
} catch(...) {
cout << "inside catch(...)" << endl;
}
} ///:~
如果在生成对象时候产生异常,会自己析购已经生成的,而产生异常的那一次生成,没有调用析构函数。
//
: C01:Cleanup.cpp
// Exceptions clean up complete objects only.
#include < iostream >
using namespace std;
class Trace {
static int counter;
int objid;
public:
Trace() {
objid = counter++;
cout << "constructing Trace #" << objid << endl;
if(objid == 3) throw 3;
}
~Trace() {
cout << "destructing Trace #" << objid << endl;
}
} ;
int Trace::counter = 0 ;
int main() {
try {
Trace n1;
// Throws exception:
Trace array[5];
Trace n2; // Won't get here.
} catch(int i) {
cout << "caught " << i << endl;
}
} ///:~
// Exceptions clean up complete objects only.
#include < iostream >
using namespace std;
class Trace {
static int counter;
int objid;
public:
Trace() {
objid = counter++;
cout << "constructing Trace #" << objid << endl;
if(objid == 3) throw 3;
}
~Trace() {
cout << "destructing Trace #" << objid << endl;
}
} ;
int Trace::counter = 0 ;
int main() {
try {
Trace n1;
// Throws exception:
Trace array[5];
Trace n2; // Won't get here.
} catch(int i) {
cout << "caught " << i << endl;
}
} ///:~