Why is the exception thrown from getA()
not caught?
#include<iostream>
using namespace std;
class Base{
protected:
int a;
public:
Base() { a=34; }
Base(int i){ a = i; }
virtual ~Base() { if(a<0) throw a; }
virtual int getA()
{
if(a < 0) { throw a;}
}
};
int main()
{
try
{
Base b(-25);
cout << endl << b.getA();
}
catch (int) {
cout << endl << "Illegal initialization";
}
}
I understand what you are saying about stack unwinding.
If I change Base
to the below, I now get my "Illegal initialization" debug to print. Why am I not getting a call to terminate()
any longer?
Base() { a=34; }
Base(int i){ a = i; if(a<0) throw a;}
virtual ~Base() { if(a<0) throw a; }
virtual int getA()
{
return a;
}
After you call getA()
the first exception is thrown, so-called stack unwinding starts and the object gets destroyed. While the object is being destroyed its destructor throws another exception that escapes the destructor's body and (since that happens during stack unwinding) this leads to terminate()
being called immediately by the C++ runtime and your program terminates.
In the second snippet you submitted the exception is thrown in the constructor, so the constructor doesn't complete and the destructor is never called (since destructors are only called for fully-constructed objects), hence no chance for terminate()
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With