Will throwing an exception in a catch block lead to two exceptions being in flight?

半世苍凉 提交于 2020-01-03 17:12:47

问题


Consider the following C++ code:

class MyException {};

void someFunction()
{
    try
    {
        /// ... code that may throw
    }
    catch(std::exception& e )
    {
        throw MyException();
    }
}

Question

Is the exception e absorbed at the beginnging of the catch block or at the end of the catch block?

In the second case throwing the new exception would result in having two exceptions in flight, what is not what I want. I want to absorb the std::exception and start one of my own type.


回答1:


No. That's how one should do it. The throw myException() can only occur if the first exception has been caught and hence is no longer 'in flight'.

This design pattern is quite common to 'translate' error messages coming from another library that your code is using to an error that the user of your code can better relate to.

Alternatively, if you want to do more than merely throw (say you want to do some clearing up of resources -- though that should really be done via RAII, i.e. from destructors), then you can simply rethrow the original exception via

try
{
    // ... code that may throw
}
catch(...) // catches anything
{
    // ... code that runs before rethrowing
    throw;    // rethrows the original catch
}



回答2:


just throw; statement is enough in catch block to rethrow same exception in higher context. It throws SAME exception again. No new exception is generated. So no fight :)

In case you want to catch exception of type A and then throw exception of type B, then the way you did it is absolute correct. In this case, old exception (type A) is caught(absorbed) and only new exception(type B) is thrown to higher context. So, again no fight :)



来源:https://stackoverflow.com/questions/33688686/will-throwing-an-exception-in-a-catch-block-lead-to-two-exceptions-being-in-flig

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