如果您通过引用捕获异常,可以修改它并重新抛出? [英] If you catch an exception by reference, can you modify it and rethrow?

查看:185
本文介绍了如果您通过引用捕获异常,可以修改它并重新抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



请考虑以下代码:

>

  class my_exception:public std :: logic_error 
{
public:
std :: vector< std ::串GT;调用堆栈;
};

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 ,那么throw-expression将被执行,并且该对象被重新引导后会有效果。


c $ c>被捕获在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆