Wednesday, April 02, 2008

C++: Rethrowing exceptions

Consider the following piece of code

catch (Base& w)
{
...
throw;
}
catch (Base& w)
{
...
throw w;
}

What do you think is the difference between the 2 approaches above .

In the first case , the exception is re thrown . In the second case a copy is made and a new exception is thrown . Also the copy is based on the static type i.e
Base (copy constructor is called )

C++ : Object Copies in C++ are based on Object's Static Type Not Dynamic Type

Consider the following piece of code

class Base { ... };
class Derived: public Base { ... };

void passAndThrowDerived()
{
Derived local;
...
Base& rw = local;

throw rw;

}


In the above mentioned case . When a copy of rw is made while throwing it .
The copy constructor for the type is called . In this case the since rw is a reference to Base there fore the copy constructor of Base is called rather than the
Copy Constructor of Derived class.

C++ : Why are objects thrown as exception always copied

When an exception is thrown , the objects are generally copied. To explain this consider the following :

{
MyObject myObject;
cin >> myObject;
throw myObject;
}

if the object myObject was passed by reference then the same myObject would be thrown out . If the same object is thrown out then as soon as it goes out of scope , its destructor would get called and as a result of which some garbage would finally reach the exceptional handling code .

It is for this reason that copies of myObject are thrown rather than the original one .