1

Can some one please explain how sequence of exceptional handling is taking place in below code? How did it evaluate to

"~B() called Handler of function try block of D()Exception in D"

#include "stdafx.h"
#include <iostream>

using namespace std;

class E {
public:
    const char* error;
    E(const char* arg): error(arg) {}
};

class B {
public:
    B() {};
    ~B(){cout<<"~B() called"<<endl;}
};

class D: public B {
public:
    D();
    ~D() { cout<<"~D() called"<<endl; }
};

D::D() try :B(){
    throw E("Exception in D");
} catch(E&e)
{
    cout<<"Handler of function try block of D()"<<e.error<<endl;
};

int main()
{
    try {
        D val;
    }catch(...) {}
}
1
  • Explain what about it? Jun 12, 2013 at 17:31

3 Answers 3

2

When you construct an object of a class which derives from another class, the base class's constructor is invoked (explicitly or implicitly) before the derived constructor body. You are throwing an exception in D's constructor body. B has already been constructed at this point. When the exception propagates out, B's destructor is called to destroy the partially-constructed object.

The second behavior of note is the rethrown exception. A function try block on a constructor always rethrows the exception. It is not possible to ignore an exception. If it were, your object would be left with B having been destroyed already. See GotW #66 for a more in-depth discussion.

0

B get's created for the Try block in the constructor of D. The throw statement ends the execution of the try block causing B to be removed by the destructor:

~B() called

There should actually be a newline here (are you not getting that or did you omit it?). Then the thrown object E enters the catch block where it is output to the screen:

Handler of function try block of D()Exception in D

Is that what you are looking for?

0

When a constructor throws an uncaught exception, base classes get automatically destructed (since they were successfully constructed before the constructor body is entered). Thus ~B() gets called before the exception handler catches the exception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.