Will throwing an exception in a catch block lead t

2019-06-27 13:51发布

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.

2条回答
放荡不羁爱自由
2楼-- · 2019-06-27 14:18

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
}
查看更多
一夜七次
3楼-- · 2019-06-27 14:31

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 :)

查看更多
登录 后发表回答