Will throwing an exception in a catch block lead to two exceptions being in flight? [duplicate]
Asked Answered
A

2

4

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.

Apple answered 13/11, 2015 at 8:40 Comment(0)
C
3

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
}
Cardiology answered 13/11, 2015 at 8:41 Comment(5)
@Default there is no point in catching and then rethrowing w/o any other action: you could obtain the same w/o the try catch block.Cardiology
@Walter: There can be many good reasons for catching and just rethrowing. Code without the catch + rethrow is not equivalent.Piperine
@Cheersandhth.-Alf can you elaborate on that? Or point me to a reference?Cardiology
not only for cleaning of resources - another example of why you would want to do throw; is to log the exception.Guiana
@Walter: For example, with the catch(...) block code in the try or called from that code, has a guarantee of local object destructors being called during stack unwinding, because there is a catch. I guess that's the most fundamental technical difference. But there are also higher level more practical differences, such as the ability to place a breakpoint.Piperine
S
1

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

Sheepshanks answered 13/11, 2015 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.