1

It's illegal to throw an exception from a function like this?
In Eclipse it work...
So it's true? and we can throw internal object in throwing exceptions?

class Bad {
    int i;
public:
    void what() { cout << "exp" << i; }
};

class A {
public:
    void f() {
        Bad e;
        throw e;
    } // e are deleted by d'tor?
};

int main() {
    A a;
    try {
        a.f();
    } catch (Bad& e) // What happen here? we catch reference to some object that
                     // was deleted by Bad dt'or
    {
        cout << "in catch";
        e.what(); // what happen here?
    }
    return 0;
}
NetVipeC
  • 4,402
  • 1
  • 17
  • 19
kasis
  • 35
  • 5
  • 1
    Quite obviously not a duplicate of that, @bames53. – Lightness Races in Orbit Sep 01 '14 at 19:23
  • Works identical to `return e;` instead of returning the local one it creates a copy. – MoonBun Sep 01 '14 at 19:25
  • @LightnessRacesinOrbit It seems pretty clear to me that it is a duplicate. http://stackoverflow.com/questions/1860064/catching-exception-objects-by-reference-temporaries-lifetime-issues Both questions are asking how it's possible that an object that gets destroyed on scope exit can be caught by reference, because shouldn't the reference be invalid at that point? – bames53 Sep 02 '14 at 16:38
  • Temporaries and local variables are not the same thing. The difference is subtle but, in the alternate reality in which you and I do not already know the answer, it could be important! – Lightness Races in Orbit Sep 02 '14 at 17:51
  • But we do know the answer and the difference is irrelevant to the answer, as the answer is the same in both cases. A single question and answer covering both temporaries and local variables is sufficient. – bames53 Sep 02 '14 at 22:07

1 Answers1

3

Your code is fine. throw e; makes a copy of e, which is destroyed after the exception has been handled. The handler is given a reference to that copy.

You could get in trouble if you threw a pointer to the local variable; the variable would be destroyed before handling the exception, leaving the pointer invalid. But throwing a pointer would be rather an odd thing to do in any case.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • @ItayAveksis: Because throwing an object is specified to make a copy of the object, since that avoids the problem you describe in the question: the object itself is destroyed during stack unwinding, before the exception is handled. It's not quite the same as `throw Bad(e)`, which that would make *two* copies: the temporary `Bad(e)`, and the copy of that that's thrown. – Mike Seymour Sep 01 '14 at 18:41