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

扶醉桌前 提交于 2019-12-20 11:35:11

问题


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.


回答1:


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)




回答2:


Yes, you can do this.

When you rethrow the current exception using throw;, no copies are made: the original temporary exception object is rethrown. Thus, any changes you make to that object in the handler will be present in the exception object when you next catch it.



来源:https://stackoverflow.com/questions/8481147/if-you-catch-an-exception-by-reference-can-you-modify-it-and-rethrow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!