How are exceptions allocated on the stack caught beyond their scope?

Posted by John Doe on Stack Overflow See other posts from Stack Overflow or by John Doe
Published on 2010-03-08T19:58:05Z Indexed on 2010/03/08 20:06 UTC
Read the original article Hit count: 246

In the following code, the stack-based variable 'ex' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (AFAIK) stack-based variables cannot be used outside the scope in which they were declared (the stack is unwound).

void f() {
    SomeKindOfException ex(...);
    throw ex;
}

void g() {
    try {
        f();
    } catch (SomeKindOfException& ex) {
        //Handling code...
    }
}

I've added a print statement to SomeKindOfException's destructor and it shows that ex is destructed once it goes out of scope in f() but then it's caught in g() and destructed again once it goes out of scope there as well.

Any help?

© Stack Overflow or respective owner

Related posts about c++

Related posts about callstack