Scope of an exception object in C ++

What is the scope of an exception object in C ++? Does it go out of scope as soon as the catch handler is executed? In addition, if I create an object of an unnamed exception and throw it, then, catching this exception, does it matter if I catch it using a constant reference or a non-constant reference?

+30
c ++ scope exception-handling
Oct 31 '09 at 11:41
source share
3 answers

When the throw expression evaluates, the exception object is initialized from the value of the expression. The highlighted exception object 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 in progress.

The object of the object of exceptions goes beyond the area in which the throw occurs. Think of it as living in a special exclusion zone on one side of a regular call stack where local objects live.

Inside the catch name initialized by the infected exception object is initialized by this exception object, and not by the throw argument, even if this value was lvalue.

If you catch through a non-const reference, you can mutate the exception object, but not from what it was initialized. You can change the behavior of the program if you re-select the exception in ways that you would not be able to if you caught by value or constant link ( const_cast to the side).

The exception object is destroyed when the last catch block completes, which does not exit through the second throw (i.e., an indifferent expression of the expression of the throw).

+31
Oct 31 '09 at 12:03
source share

The exception object is available only in the catch . You cannot use an exception object outside of a catch . The following steps occur when you throw an exception and catch:

 try { MyException anObject; throw anObject; //1 } catch(MyException exObject) { } 
  • The throw clause (// 1) receives a local anObject and treats it as an argument to the value: it creates a copy of anObject .
  • the catch handler catches the MyException object, which again is a value parameter. At this point, another copy is created.
  • If the catch handler would be implemented to get a reference to the object (catch (MyException &o)) , then the second copy will be eliminated.
  • If the catch handler receives the exception object using const& , then you can only call const methods.
+8
Oct 31 '09 at 12:33
source share

First of all, the object that you drop out of scope almost immediately. What the exception handlers will catch is a copy of the original object. This copy will be deleted after the capture handler is executed, unless you catch it by value (not by reference). In this case, another copy will be created. But you have to catch it by reference (preferably const one) anyway.

+4
Oct 31 '09 at 11:52
source share



All Articles