J
junw2000
Hi,
Below is a simple code about exception.
#include <iostream>
using namespace std;
struct E {
const char* message;
E(const char* arg) : message(arg) { }
};
void my_terminate() {
cout << "Call to my_terminate" << endl;
};
struct A {
A() { cout << "In constructor of A" << endl; }
~A() {
cout << "In destructor of A" << endl;
throw E("Exception thrown in ~A()");
}
};
struct B {
B() { cout << "In constructor of B" << endl; }
~B() { cout << "In destructor of B" << endl; }
};
int main() {
set_terminate(my_terminate);
try {
cout << "In try block" << endl;
A a;
B b;
cout << "Leave try block" << endl;
throw("Exception thrown in try block of main()"); //LINE1
}
catch (const char* e) { //LINE2
cout << "Exception: " << e << endl; //LINE3
}
catch (...) {
cout << "Some exception caught in main()" << endl;
}
cout << "Resume execution of main()" << endl;
}
The output of the code is below:
In try block
In constructor of A
In constructor of B
Leave try block
In destructor of B
In destructor of A
Call to my_terminate
Abort
My question is when LINE1 throws an exception, the exception is caught
by LINE2, right?
Why LINE3 does not output anything?
The last line of the output is "Abort". Why is it from? Does the
function my_terminate() output the "Abort"?
Thanks
Jack
Below is a simple code about exception.
#include <iostream>
using namespace std;
struct E {
const char* message;
E(const char* arg) : message(arg) { }
};
void my_terminate() {
cout << "Call to my_terminate" << endl;
};
struct A {
A() { cout << "In constructor of A" << endl; }
~A() {
cout << "In destructor of A" << endl;
throw E("Exception thrown in ~A()");
}
};
struct B {
B() { cout << "In constructor of B" << endl; }
~B() { cout << "In destructor of B" << endl; }
};
int main() {
set_terminate(my_terminate);
try {
cout << "In try block" << endl;
A a;
B b;
cout << "Leave try block" << endl;
throw("Exception thrown in try block of main()"); //LINE1
}
catch (const char* e) { //LINE2
cout << "Exception: " << e << endl; //LINE3
}
catch (...) {
cout << "Some exception caught in main()" << endl;
}
cout << "Resume execution of main()" << endl;
}
The output of the code is below:
In try block
In constructor of A
In constructor of B
Leave try block
In destructor of B
In destructor of A
Call to my_terminate
Abort
My question is when LINE1 throws an exception, the exception is caught
by LINE2, right?
Why LINE3 does not output anything?
The last line of the output is "Abort". Why is it from? Does the
function my_terminate() output the "Abort"?
Thanks
Jack