Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught exception

Tags:

c++

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";
    }
}

EDIT:

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;
}
like image 515
thikonom Avatar asked Dec 02 '22 03:12

thikonom


1 Answers

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.

like image 87
sharptooth Avatar answered Dec 25 '22 12:12

sharptooth