C++ the scope of exception parameter

Table of Contents

Look at code:

#include <iostream>
#include <string>

using namespace std;

void some_function()
{
    string str("Hello,World!");
    throw(str);
}

int main()
{
    try
    {
        some_function();
    }
    catch (string& e)
    {
        cout << e << endl;
        e = "Hello, the world!";
        cout << e << endl;
    }

    return 0;
}

Debug it in VS2010, I get that information:

  1. in somefunction the str addr: 0x003CF820
  2. int main the e addr: 0x003CF738

So, I have three question:

  1. catch parameter is string&, why we get diff addr in main() ?
  2. is str not a temp value ? why we can use a temp value reference ?
  3. where is e store in memory ?

One Answer make me understand:

When a throw expression is evaluated, an exception object is initialized from the value of the expression. The exception object which is thrown gets its type from the static type of the throw expression ignoring any const and volatile qualifiers. For class types this means that copy-initialization is performed.

The exception object's scope is outside of the scope of the block where the throw occurs. Think of it as living in a special exception area off to one side of the normal call stack where local objects live.

Inside a catch block, the name initialized with the caught exception object is initialized with this exception object and not the argument to throw, even if this was an lvalue.

If you catch via non-const reference, then you can mutate the exception object, but not what it was initialized from. You can alter the behaviour of the program if you re-throw the exception in ways that you couldn't if you caught by value or const reference (constcasts aside).

The exception object is destroyed when the last catch block that does not exit via a re-throw (i.e. a parameterless throw expression evaluation) completes.

thanks for Charles Bailey.

1 Reference

Date: 2014-01-14 00:00:00

Author: JerryZhang