How Many Copies Are Made When Throwing a C++ Exception?

February 3, 2014, updated February 3, 2014

This is a simple exercise in demonstrating what happens to an object that is thrown. Given the following code, how many times is the constructor called and how many times is the copy constructor called?

#include <iostream>
using namespace std;
 
class Object
{
public:
   Object(int value = 0)
      : mValue(value)
   {
      cout << "constructor" << endl;
   }
 
   Object(const Object& rhs)
   {
      cout << "copy constructor" << endl;
      mValue = rhs.mValue;
   }
 
   int mValue;
};
 
int main()
{
   Object object(101);
   try
   {
      throw object;
   }
   catch(Object object)
   {
      cout << "caught exception " << object.mValue << endl;
   }
 
   return 0;
}

Have your guess? Well, here's the output.

$ ./throw 
constructor
copy constructor
copy constructor
caught exception 101

What this demonstrates is that a copy is made when you call throw, and because the exception is caught by value, another copy is made. The lesson here is to catch your exception by reference:

catch(const Object& object)

Also remember to only throw exceptions in exceptional cases. Not as a generic error handling method.

Related Posts