Question

Scope of exception object in C++

What is the scope of the exception object in C++? does it go out of scope as soon as catch handler is executed? Also, if I create an unnamed exception object and throw it, then while catching that exception does it matter if I catch it by const reference or a non-const reference?

 45  11271  45
1 Jan 1970

Solution

 44

When a throw expression is evaluated, an exception object is initialized from the value of the expression. The exception object which is thrown gets its type from the static type of the throw expression ignoring any const and volatile qualifiers. For class types this means that copy-initialization is performed.

The exception object's scope is outside of the scope of the block where the throw occurs. Think of it as living in a special exception area off to one side of the normal call stack where local objects live.

Inside a catch block, the name initialized with the caught exception object is initialized with this exception object and not the argument to throw, even if this was an lvalue.

If you catch via non-const reference, then you can mutate the exception object, but not what it was initialized from. You can alter the behaviour of the program if you re-throw the exception in ways that you couldn't if you caught by value or const reference (const_casts aside).

The exception object is destroyed when the last catch block that does not exit via a re-throw (i.e. a parameterless throw expression evaluation) completes.

2009-10-31

Solution

 9

The exception object is available only in catch block. You cannot use the exception object outside the catch block. Following steps happen when you throw an exception and catch:

try
{
 MyException anObject;
 throw anObject;  //1

}
catch(MyException exObject)
{
}
  • The throw clause (//1) receives the local object anObject, and treats it as a value argument: it creates a copy of the anObject.
  • the catch handler catches an MyException Object,which again is a value parameter. At this moment another copy is created.
  • If the catch handler would have implemented so as to receive a reference to an object (catch (MyException &o)), the second copy is avoided.
  • if catch handler receives the exception object by const& then you can only call const methods.
2009-10-31