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.

Knitschi
  • 2,822
  • 3
  • 32
  • 51

2 Answers2

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
}
Walter
  • 44,150
  • 20
  • 113
  • 196
  • @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. – Walter Nov 13 '15 at 08:47
  • 1
    @Walter: There can be many good reasons for catching and just rethrowing. Code without the `catch` + rethrow is not equivalent. – Cheers and hth. - Alf Nov 13 '15 at 08:48
  • 1
    @Cheersandhth.-Alf can you elaborate on that? Or point me to a reference? – Walter Nov 13 '15 at 08:59
  • not only for cleaning of resources - another example of why you would want to do `throw;` is to log the exception. – default Nov 13 '15 at 09:07
  • 2
    @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. – Cheers and hth. - Alf Nov 13 '15 at 09:34
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 :)

NightFurry
  • 358
  • 1
  • 17