Home > Articles > Programming > C/C++

This chapter is from the book

This chapter is from the book

11.3 Catching an Exception

A C++ exception handler is a catch clause. When an exception is thrown from statements within a try block, the list of catch clauses that follows the try block is searched to find a catch clause that can handle the exception.

A catch clause consists of three parts: the keyword catch, the declaration of a single type or single object within parentheses (referred to as an exception declaration), and a set of statements within a compound statement. If the catch clause is selected to handle an exception, the compound statement is executed. Let's examine the catch clauses for the exceptions pushOnFull and popOnEmpty in the function main() in more detail.

catch ( pushOnFull ) {
   cerr << "trying to push a value on a full stack\n";
   return errorCode88;
}
catch ( popOnEmpty ) {
   cerr << "trying to pop a value on an empty stack\n";
   return errorCode89;
}

Both catch clauses have an exception declaration of class type; the first one is of type pushOnFull, and the second one is of type popOnEmpty. A handler is selected to handle an exception if the type of its exception declaration matches the type of the exception thrown. (We will see in Chapter 19 that the types do not have to match exactly: a handler for a base class can handle exceptions of a class type derived from the type of the handler's exception declaration.) For example, when the pop() member function of the class iStack throws a popOnEmpty exception, the second catch clause is entered. After an error message is issued to cerr, the function main() returns errorCode89.

If these catch clauses do not contain a return statement, where does the execution of the program continue? After a catch clause has completed its work, the execution of the program continues at the statement that follows the last catch clause in the list. In our example, the execution of the program continues with the return statement in main() and, after the catch clause for popOnEmpty generates an error message to cerr, main() returns the value 0.

int main() {
   iStack stack( 32 );

   try {
      stack.display();
      for ( int ix = 1; ix < 51; ++ix )
      {
         // same as before
      }
   }
   catch ( pushOnFull ) {
      cerr << "trying to push a value on a full stack\n";
   }
   catch ( popOnEmpty ) {
      cerr << "trying to pop a value on an empty stack\n";
   }

   // execution of the program continues here
   return 0;
}

The C++ exception handling mechanism is said to be nonresumptive; once the exception has been handled, the execution of the program does not resume where the exception was originally thrown. In our example, once the exception has been handled, the execution of the program does not continue in the pop() member function where the exception was thrown.

11.3.1 Exception Objects

The exception declaration of a catch clause can be either a type declaration or an object declaration. When should the exception declaration in a catch clause declare an object? An object should be declared when it is necessary to obtain the value or manipulate the exception object created by the throw expression. If we design our exception classes to store information in the exception object when the exception is thrown and if the exception declaration of the catch clause declares an object, the statements within the catch clause can use this object to refer to the information stored by the throw expression.

For example, let's change the design of the pushOnFull exception class. Let's store within the exception object the value that cannot be pushed on the stack. The catch clause is changed to display this value when the error message is generated to cerr. To do this, we first need to change the definition of the pushOnFull class type. Here is our new definition:

// new exception class:
// it stores the value that cannot be pushed on the stack
class pushOnFull {
public:
   pushOnFull( int i ) : _value( i ) { }
   int value() { return _value; }
private:
   int _value;
};

The new private data member _value holds the value that cannot be pushed on the stack. The constructor takes a value of type int and stores this value in the _value data member. Here is how the constructor can be invoked by the throw expression to store in the exception object the value that cannot be pushed on the stack:

void iStack::push( int value )
{
   if ( full() )
      // value stored in exception object
      throw pushOnFull( value );
   // ...
}

The class pushOnFull also has a new member function value() that can be used in the catch clause to display the value stored in the exception object. Here is how it can be used:

catch ( pushOnFull eObj ) {
   cerr << "trying to push the value " << eObj.value()
        << " on a full stack\n";
}

Notice that the catch clause's exception declaration declares the object eObj, which is used to invoke the member function value() of the class pushOnFull.

An exception object is always created at the throw point even though the throw expression is not a constructor call and even though it doesn't appear to be creating an exception object. For example:

enum EHstate { noErr, zeroOp, negativeOp, severeError };
enum EHstate state = noErr;

int mathFunc( int i ) {
   if ( i == 0 ) {
      state = zeroOp;
      throw state; // exception object created
   }
   // otherwise, normal processing continues
}

In this example, the object state is not used as the exception object. Instead, an exception object of type EHstate is created by the throw expression and initialized with the value of the global object state. How can a program tell that the exception object is distinct from the global object state? To answer this question we must first look at the catch clause exception declaration in more detail.

The exception declaration of a catch clause behaves very much like a parameter declaration. When a catch clause is entered, if the exception declaration declares an object, this object is initialized with a copy of the exception object. For example, the following function calculate() calls the function mathFunc() defined earlier. When the catch clause in calculate() is entered, the object eObj is initialized with a copy of the exception object created by the throw expression:

void calculate( int op ) {
   try {
      mathFunc( op );
   }
   catch ( EHstate eObj ) {
      // eObj is a copy of the exception object thrown
   }
}

The exception declaration in this example resembles a pass-by-value parameter. The object eObj is initialized with the value of the exception object in the same way that a pass-by-value function parameter is initialized with the value of the corresponding argument (pass-by-value parameters are discussed in Section 7.3).

As is the case for function parameters, the exception declaration of a catch clause can be changed to a reference declaration. The catch clause then directly refers to the exception object created by the throw expression instead of creating a local copy. For example:

void calculate( int op ) {
   try {
      mathFunc( op );
   }
   catch ( EHstate &eObj ) {
      // eObj refers to the exception object thrown
   }
}

For the same reasons that parameters of class type should be declared as references to prevent unnecessary copying of large class objects, it is also preferable if exception declarations for exceptions of class type are declared as references.

With an exception declaration of reference type, the catch clause is able to modify the exception object. However, any variable specified by the throw expression remains unaffected. For example, modifying eObj within the catch clause does not affect the global variable state specified by the throw expression:

void calculate( int op ) {
   try {
      mathFunc( op );
   }
   catch ( EHstate &eObj ) {
      // fix exception situation
      eObj = noErr; // global variable state is not modified
   }
}

The catch clause resets eObj to the value noErr after correcting the exception situation. Because eObj is a reference, we can expect this assignment to modify the global object state. However, the assignment modifies only the exception object created by the throw expression. And because the exception object is a distinct object from the global object state, state remains unchanged by the modification to eObj in the catch clause.

11.3.2 Stack Unwinding

The search for a catch clause to handle a thrown exception proceeds as follows: if the throw expression is located within a try block, the catch clauses associated with this try block are examined to see whether one of these clauses can handle the exception. If a catch clause is found, the exception is handled. If no catch clause is found, the search continues in the calling function. If the call to the function exiting with the thrown exception is located within a try block, the catch clauses associated with this try block are examined to see whether one can handle the exception. If a catch clause is found, the exception is handled. If no catch clause is found, the search continues in the calling function. This process continues up the chain of nested function calls until a catch clause for the exception is found. As soon as a catch clause that can handle the exception is encountered, the catch clause is entered and the execution of the program continues within this handler.

In our example, the first function that is searched for a catch clause is the pop() member function of the class iStack. Because the throw expression in pop() is not located within a try block, pop() exits with an exception. The next function examined is the function that calls the member function pop(), which is main() in our example. The call of pop() in main() is located within a try block. The catch clauses associated with this try block are considered to handle the exception. A catch clause for exceptions of type popOnEmpty is found and entered to handle the exception.

The process by which compound statements and function definitions exit because of a thrown exception in the search for a catch clause to handle the exception is called stack unwinding. As the stack is unwound, the lifetime of local objects declared in the compound statements and in function definitions that are exited ends. C++ guarantees that, as the stack is unwound, the destructors for local class objects are called even though their lifetime ends because of a thrown exception. We look into this in more detail in Chapter 19.

What if the program does not provide a catch clause for the exception that is thrown? An exception cannot remain unhandled. An exception is an important enough situation that the program cannot continue executing normally. If no handler is found, the program calls the terminate() function defined in the C++ standard library. The default behavior of terminate() is to call abort(), indicating the abnormal exit from the program. (In most situations, calling abort() is good enough. However, in some cases it is necessary to override the actions performed by terminate(). [STROUSTRUP94] shows how this can be done and discusses it in more detail.)

By now, you will probably have noticed many similarities between exception handling and function calls. A throw expression behaves somewhat like a function call, and the catch clause behaves somewhat like a function definition. The main difference between these two mechanisms is that all the information necessary to set up a function call is available at compile-time, and that is not true for the exception handling mechanism. C++ exception handling requires run-time support. For example, for an ordinary function call, the compiler knows at the point of the call which function will actually be called through the process of function overload resolution. For exception handling, the compiler does not know for a particular throw expression in which function the catch clause resides and where execution resumes after the exception has been handled. These decisions happen at run-time. The compiler cannot inform users when no handler exists for an exception. This is why the terminate() function exists: it is a run-time mechanism to tell users when no handler matches the exception thrown.

11.3.3 Rethrow

It is possible that a single catch clause cannot completely handle an exception. After some corrective actions, a catch clause may decide that the exception must be handled by a function further up the list of function calls. A catch clause can pass the exception to another catch clause further up the list of function calls by rethrowing the exception. A rethrow expression has this form:

throw;

A rethrow expression rethrows the exception object. A rethrow can appear only in the compound statement of a catch clause. For example:

catch ( exception eObj ) {
   if ( canHandle( eObj ) )
      // handle the exception
      return;
   else
      // rethrow it for another catch clause to handle
      throw;
}

The exception that is rethrown is the original exception object. This has some implications if the catch clause modifies the exception object before rethrowing it. The following does not modify the original exception object. Can you see why?

enum EHstate { noErr, zeroOp, negativeOp, severeError };

void calculate( int op ) {
   try {
      // exception thrown by mathFunc() has value zeroOp
      mathFunc( op );
   }
   catch ( EHstate eObj ) {
      // fix a few things

      // attempt to modify the exception object
      eObj = severeErr;

      // intends to rethrow an exception of value severeErr
      throw;
   }
}

Because eObj is not a reference, the catch clause receives a copy of the exception object, and any modifications to eObj within the handler modify the local copy. They do not affect the original exception object created by the throw expression. It is this original exception object that is rethrown by the rethrow expression. Because the original exception is not modified within the catch clause in our example, the object rethrown still has its initial zeroOp value.

To modify the original exception object, the exception declaration within the catch clause must declare a reference. For example:

catch ( EHstate &eObj ) {
   // modifies the exception object
   eObj = severeErr;

   // The value of the exception rethrown is severeErr
   throw;
}

eObj refers to the exception object created by the throw expression, and modifications to eObj in the catch clause affect the original exception object. These modifications are part of the exception object that is rethrown.

Therefore, another good reason to declare the exception declaration of the catch clause as a reference is to ensure that modifications applied to the exception object within the catch clause are reflected in the exception object that is rethrown. We will see another good reason why exception declarations for exceptions of class type should be references in Section 19.2, where we see how catch clauses can invoke the class virtual functions.

11.3.4 The Catch-All Handler

A function may want to perform some action before it exits with a thrown exception even though it cannot handle the exception that is thrown. For example, a function may acquire some resource, such as opening a file or allocating memory on the heap, and it may want to release this resource (close the file or release the memory) before it exits with the thrown exception. For example:

void manip() {
   resource res;
   res.lock();    // locks a resource

   // use res
   // some action that causes an exception to be thrown

   res.release(); // skipped if exception thrown
}

The release of the resource res is bypassed if an exception is thrown. To guarantee that the resource is released, rather than provide a specific catch clause for every possible exception and because we can't know all the exceptions that might be thrown, we can use a catch-all catch clause. This catch clause has an exception declaration of the form (...) , where the three dots are referred to as an ellipsis. This catch clause is entered for any type of exception. For example:

// entered with any exception thrown
catch ( ... ) {
   // place our code here
}

A catch(...) is used in combination with a rethrow expression. The resource that has been locked is released within the compound statement of the catch clause before the exception is propagated further up the list of function calls with a rethrow expression:

void manip() {
   resource res;
   res.lock();
   try {
      // use res
      // some action that causes an exception to be thrown
   }
   catch (...) {
        res.release();
        throw;
   }
   res.release(); // skipped if exception thrown
}

To ensure that the resource is appropriately released if an exception is thrown and manip() exits with an exception, a catch(...) is used to release the resource before the exception is propagated to functions further up the list of function calls. We can also manage the acquisition and release of a resource by encapsulating the resource in a class, and having the class constructor acquire the resource and the class destructor release the resource automatically. We look at how to do this in Chapter 19.

A catch (...) clause can be used by itself or in combination with other catch clauses. If it is used in combination with other catch clauses, we must take some care when organizing the set of catch clauses associated with the try block.

Catch clauses are examined in turn, in the order in which they appear following the try block. Once a match is found, subsequent catch clauses are not examined. This implies that if a catch (...) is used in combination with other catch clauses, it must always be placed last in a list of exception handlers; otherwise, a compiler error is issued. For example:

try {
   stack.display();
   for ( int ix = 1; ix < 51; ++ix )
   {
      // same as before
   }
}
catch ( pushOnFull ) { }
catch ( popOnEmpty ) { }
catch (...) { } // must be last catch clause

Exercise 11.4

Explain why we say that the C++ exception handling model is nonresumptive.

Exercise 11.5

Given the following exception declarations, provide a throw expression that creates an exception object that can be caught by the following catch clauses.

(a) class exceptionType { };
    catch( exceptionType *pet ) { }
(b) catch(...) { }
(c) enum mathErr { overflow, underflow, zeroDivide };
    catch( mathErr &ref ) { }
(d) typedef int EXCPTYPE;
    catch( EXCPTYPE ) { }

Exercise 11.6

Explain what happens during stack unwinding.

Exercise 11.7

Give two reasons that the exception declaration of a catch clause should declare a reference.

Exercise 11.8

Using the code you developed for Exercise 11.3, modify the exception class you created so that the invalid index used with operator[]() is stored in the exception object when the exception is thrown and later displayed by the catch clause. Modify your program so that operator[]() throws an exception during the execution of the program.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020