如果你通过引用捕获异常,你能修改它并重新抛出吗? [英] If you catch an exception by reference, can you modify it and rethrow?
问题描述
请考虑下面的代码:
class my_exception:public std :: logic_error
{
public:
std :: vector< std :: string>调用堆
};
void MyFunc()
{
try
{
SomethingThatThrows();
}
catch(my_exception& e)
{
e.callstack.push_back(MyFunc);
throw;
}
}
这是一个假设的例子,尝试这样的东西。我只是想知道会发生什么,基于另一个线程的建议,异常应该被 const 引用捕获。
异常会改变。
§15.3[except.handle] / 17:
< >
当处理程序声明非常量对象时,对该对象的任何更改都不会影响由执行throw-expression初始化的临时
对象。
当处理程序声明对
a非常量对象的引用时,对引用对象的任何更改都将更改为初始化的临时对象
因此,如果 my_exception
在 MyFunc
之外捕获,我们将在callstack中看到MyFunc
http://ideone.com/5ytqN )
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.
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)
这篇关于如果你通过引用捕获异常,你能修改它并重新抛出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!