tags:

views:

135

answers:

2

In C++, what is the difference between the following examples?

Re-throw pointer:

catch (CException* ex)
{
    throw ex;
}

Simple re-throw:

catch (CException* ex)
{
    throw;
}

When the re-throw is caught, will the stack trace be different?

+7  A: 

Yes. Basically, you are throwing the object yourself in the first case. It looks like you generated the exception yourself in the throw ex line. In the second case, you are just letting the original object go up in the call stack (and thus preserving the original call stack), those are different. Usually, you should be using throw;.

Mehrdad Afshari
A: 

I think there is a performance difference. The second version will not make a temporary copy of the exception. The first will create a copy, therefore the seond is the way to go.

You could create a simple exception class and try it out, have the constructor/copy constructor print to the console when they are fired. That way you should see the difference.

martsbradley
A copy will not be constructed in the first case because the pointer is being thrown.
Aidan Ryan
I read it as he said the pointer is copied. And wondered why he thinks that made a performance difference. Now i see what he was thinking of. Yeah, it's wrong only the pointer is copied, and the copy can be elided.
Johannes Schaub - litb