Answer
The output for the quiz code is:
Function g called with -1
R 1 created
R 2 created
R 1 destroyed
E caught
Function g called with 1
R 1 created
R 2 created
Function g called with 0
R 1 created
R 2 created
Function g called with -1
R 1 created
R 2 created
R 1 destroyed
R 1 destroyed
R 1 destroyed
E2 caught
Exception caught
Problem
#include < iostream.h >
class Resource {
int x;
public:
Resource (int y): x(y)
{ cout << "R " << x << " created " << endl; }
~Resource ()
{ cout << "R " << x << " destroyed " << endl; }
};
class Error {
public:
virtual void p ()
{ cout << "E caught"<< endl; }
};
class Error2 : public Error {
public:
virtual void p () { cout << "E2 caught "<< endl; }
};
void g (int x) throw (Error, Error2);
void g (int x) {
cout << "Function g called with " << x << endl;
Resource r1(1);
Resource* r2 = new Resource (2);
if (x < 0 )
throw Error2();
else
g(x-1);
delete r2;
}
void h () {
try {
g(-1);
} catch (Error e) {
e.p();
}
try {
g(1);
} catch (Error & e) {
e.p();
throw;
}
}
void main() {
try {
h();
}
catch ( ... ) {
cout << "Exception caught" << endl;
}
}