Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you catch an exception by reference, can you modify it and rethrow?

Tags:

Does the standard have anything to say about an exception that is caught by reference and what happens to attempts to modify it?

Consider the following code:

class my_exception: public std::logic_error
{
public:
    std::vector<std::string> callstack;
};

void MyFunc()
{
    try
    {
        SomethingThatThrows();
    }
    catch (my_exception & e)
    {
        e.callstack.push_back("MyFunc");
        throw;
    }
}

This is a contrived example, I'm not actually attempting something like this. I was just curious what would happen, based on the suggestion in another thread that exceptions should be caught by const reference.

like image 341
Mark Ransom Avatar asked Dec 12 '11 21:12

Mark Ransom


1 Answers

The exception will change.

§15.3[except.handle]/17:

When the handler declares a non-constant object, any changes to that object will not affect the temporary object that was initialized by execution of the throw-expression.

When the handler declares a reference to a non-constant object, any changes to the referenced object are changes to the temporary object initialized when the throw-expression was executed and will have effect should that object be rethrown.

So if my_exception is caught outside of MyFunc, we'll see the "MyFunc" entry in the callstack (e.g. http://ideone.com/5ytqN)

like image 176
kennytm Avatar answered Nov 02 '22 23:11

kennytm