Aidan Ryan
Aidan Ryan

Reputation: 11609

Re-throwing exception caught by pointer

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?

Upvotes: 1

Views: 288

Answers (2)

martsbradley
martsbradley

Reputation: 158

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.

Upvotes: -2

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422122

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;.

Upvotes: 7

Related Questions