Book: C++ Primer, Third Edition
Section: Chapter 11. Exception Handling

11.1 Throwing an Exception

Exceptions are run-time anomalies that a program may detect, such as division by 0, access to an array outside of its bounds, or the exhaustion of the free store memory. Such exceptions exist outside the normal functioning of the program and require immediate handling by the program. The C++ language provides built-in language features to raise and handle exceptions. These language features activate a run-time mechanism used to communicate exceptions between two unrelated (often separately developed) portions of a C++ program.
When an exception is encountered in a C++ program, the portion of the program that detects the exception can communicate that the exception has occurred by raising, or throwing, an exception. To see how exceptions are thrown in C++, let's reimplement the class iStack presented in Section 4.15 to use exceptions to indicate anomalies in the handling of the stack. The definition of the class iStack looks like this:
#include <vector>
class iStack {
public:
iStack( int capacity )
: _stack( capacity ), _top( 0 ) { }
bool pop( int &top_value );
bool push( int value );
bool full();
bool empty();
void display();
int size();
private:
int _top;
vector< int > _stack;
};
The stack is implemented using a vector of ints. When an iStack object is created, the constructor for iStack creates a vector of ints of the size specified with the initial value. This size is the maximum number of elements the iStack object can contain. The following, for example, creates an iStack object called myStack that can contain as many as 20 values of type int:
iStack myStack(20);
What can go wrong when we manipulate myStack? Here are two anomalies that may be encountered with our iStack class:
  1. A pop() operation is requested and the stack is empty.
  2. A push() operation is requested and the stack is full.
We decide that these anomalies should be communicated to the functions manipulating iStack objects using exceptions. So where do we start?
First, we must define the exceptions that can be thrown. In C++, exceptions are most often implemented using classes. Although classes are fully introduced in Chapter 13, we will define here two simple classes to use as exceptions with our iStack class, and we place these class definitions in the header stackExcp.h:
// stackExcp.h
class popOnEmpty { /* ... */ };
class pushOnFull { /* ... */ };
Chapter 19 discusses exceptions of class type in greater detail and discusses the exception class hierarchy provided by the C++ standard library.
We must then change the definition of the member functions pop() and push() to throw these newly defined exceptions. An exception is thrown using a throw expression. A throw expression looks a great deal like a return statement. A throw expression is composed of the keyword throw followed by an expression whose type is that of the exception thrown. What does the throw expression in pop() look like? Let's try this:
// oops, not quite right
throw popOnEmpty;
Unfortunately, this is not quite right. An exception is an object, and pop() must throw an object of class type. The expression in the throw expression cannot simply be a type. To create an object of class type, we need to call the class constructor. What does a throw expression that invokes a constructor look like? Here is the throw expression in pop():
// expression is a constructor call
throw popOnEmpty();
This throw expression creates an exception object of type popOnEmpty.
Recall that the member functions pop() and push() were defined to return a value of type bool: a true return value indicates that the operation succeeded, and a false return value indicates that it failed. Because exceptions are now used to indicate the failure of the pop() and push() operations, the return values from these functions are now unnecessary. We now define these member functions with a void return type. For example:
class iStack {
public:
// ...
// no longer return a value
void pop( int &value );
void push( int value );
private:
// ...
};
The functions that use our iStack class will now assume that everything is fine unless an exception is thrown; they no longer need to test the return value of the member function pop() or push() to see whether the operation succeeds. We will see how to define a function to handle exceptions in the next two sections.
We are now ready to provide the new implementations of iStack's pop() and push() member functions:
#include "stackExcp.h"
void iStack::pop( int &top_value )
{
if ( empty() )
throw popOnEmpty();
top_value = _stack[ --_top ];
cout < "iStack::pop(): " < top_value < endl;
}
void iStack::push( int value )
{
cout < "iStack::push( " < value < " )\n";
if ( full() )
throw pushOnFull();
_stack[ _top++ ] = value;
}
Although exceptions are most often objects of class type, a throw expression can throw an object of any type. For example, although it's unusual, the function mathFunc() in the following code sample throws an exception object of enumeration type. This code is valid C++ code:
enum EHstate { noErr, zeroOp, negativeOp, severeError };
int mathFunc( int i ) {
if ( i == 0 )
throw zeroOp; // exception of enumeration type
// otherwise, normal processing continues
}
Exercise 11.1
Which, if any, of the following throw expressions are errors? Why? For the valid throw expressions, indicate the type of the exception thrown.
(a) class exceptionType { };
throw exceptionType();
(b) int excpObj;
throw excpObj;
(c) enum mathErr { overflow, underflow, zeroDivide };
throw zeroDivide();
(d) int *pi = &excpObj;
throw pi;
Exercise 11.2
The IntArray class defined in Section 2.3 has a member operator function operator[]() that uses assert() to indicate that the index is outside the bounds of the array. Change the definition of operator[]() to instead throw an exception in this situation. Define an exception class to be used as the type of the exception thrown.
URL
Book: C++ Primer, Third Edition
Section: Chapter 11. Exception Handling

11.2 The Try Block

The following small program exercises our class iStack and the pop() and push() member functions defined in the previous section. The for loop in main() iterates 50 times. It pushes on the stack each value that is a multiple of 3 — 3, 6, 9, and so on. Whenever the value is a multiple of 4, such as 4, 8, 12, and so on, it displays the contents of the stack. Whenever the value is a multiple of 10, such as 10, 20, 30, and so on, it pops the last item from the stack and then displays the contents of the stack again. How do we change main() to handle the exceptions thrown by the iStack member functions?
#include <iostream>
#include "iStack.h"
int main() {
iStack stack( 32 );
stack.display();
for ( int ix = 1; ix < 51; ++ix )
{
if ( ix % 3 == 0 )
stack.push( ix );
if ( ix % 4 == 0 )
stack.display();
if ( ix % 10 == 0) {
int dummy;
stack.pop( dummy );
stack.display();
}
}
return 0;
}
A try block must enclose the statements that can throw exceptions. A try block begins with the try keyword followed by a sequence of program statements enclosed in braces. Following the try block is a list of handlers called catch clauses. The try block groups a set of statements and associates with these statements a set of handlers to handle the exceptions that the statements can throw. Where should we place a try block or try blocks in the function main() to handle the exceptions popOnEmpty and pushOnFull? Let's try this:
for ( int ix = 1; ix < 51; ++ix ) {
try { // try block for pushOnFull exceptions
if ( ix % 3 == 0 )
stack.push( ix );
}
catch ( pushOnFull ) { ... }
if ( ix % 4 == 0 )
stack.display();
try { // try block for popOnEmpty exceptions
if ( ix % 10 == 0 ) {
int dummy;
stack.pop( dummy );
stack.display();
}
}
catch ( popOnEmpty ) { ... }
}
The program as we have implemented it works correctly. Its organization, however, intermixes the handling of the exceptions with the normal processing of the program and thus is not ideal. After all, exceptions are program anomalies that occur only in exceptional cases. We want to separate the code that handles the program anomalies from the code that implements the normal manipulation of the stack. We believe that this strategy makes the code easier to follow and easier to maintain. Here is our preferred solution:
try {
for ( int ix = 1; ix < 51; ++ix )
{
if ( ix % 3 == 0 )
stack.push( ix );
if ( ix % 4 == 0 )
stack.display();
if ( ix % 10 == 0 ) {
int dummy;
stack.pop( dummy );
stack.display();
}
}
}
catch ( pushOnFull ) { ... }
catch ( popOnEmpty ) { ... }
Associated with the try block are two catch clauses that are capable of handling the exceptions pushOnFull and popOnEmpty that may be thrown from the iStack member functions push() and pop() called from within the try block. Each catch clause specifies within parentheses the type of exception it handles. The code to handle the exception is placed in the compound statement of the catch clause (between the curly braces). We examine catch clauses in greater detail in the next section.
The program control flow in our example is one of the following.
  1. If no exception occurs, the code within the try block is executed and the handlers associated with the try block are ignored. The function main() returns 0.
  2. If the push() member function called within the first if statement of the for loop throws an exception, the second and third if statements of the for loop are ignored, the for loop and the try block are exited, and the handler for exceptions of type pushOnFull is executed.
  3. If the pop() member function called within the third if statement of the for loop throws an exception, the call to display() is ignored, the for loop and the try block are exited, and the handler for exceptions of type popOnEmpty is executed.
When an exception is thrown, the statements following the statement that throws the exception are skipped. Program execution resumes in the catch clause handling the exception. If no catch clause capable of handling the exception exists, program execution resumes in the function terminate() defined in C++ standard library. We further discuss the function terminate() in the next section.
A try block can contain any C++ statement — expressions as well as declarations. A try block introduces a local scope, and variables declared within a try block cannot be referred to outside the try block, including within the catch clauses. For example, we could rewrite our function main() so that the declaration of the variable stack appears within the try block. In this case, it is not possible to refer to stack in the catch clauses:
int main() {
try {
iStack stack( 32 ); // ok: declaration in try block
stack.display();
for ( int ix = 1; ix < 51; ++ix )
{
// same as before
}
}
catch ( pushOnFull ) {
// cannot refer to stack here
}
catch ( popOnEmpty ) {
// cannot refer to stack here
}
// cannot refer to stack here
return 0;
}
It is possible to declare a function so that the entire body of the function is contained within the try block. In such a case, instead of placing the try block within the function definition we can enclose the function body within a function try block. This organization supports the cleanest separation between the code that supports the normal processing of the program and the code that supports the handling of the exceptions. For example:
int main()
try {
iStack stack( 32 );
stack.display();
for ( int ix = 1; ix < 51; ++ix )
{
// same as before
}
return 0;
}
catch ( pushOnFull ) {
// cannot refer to stack here
}
catch ( popOnEmpty ) {
// cannot refer to stack here
}
Notice that the try keyword comes before the opening brace of the function body and the catch clauses are listed after the function body's closing brace. With this code organization, the code that supports the normal processing of main() is placed within the function body, clearly separated from the code that handles the exceptions in the catch clauses. However, variables declared within main()'s function body cannot be referred to within the catch clauses.
A function try block associates a group of catch clauses with a function body. If a statement within the function body throws an exception, the handlers that follow the function body are considered to handle the exception. Function try blocks are particularly useful with class constructors. We will reexamine function try blocks in this context in Chapter 19.
Exercise 11.3
Write a program that defines an IntArray object (where IntArray is the class type defined in Section 2.3) and performs the following actions. We have three files containing integer values.
  1. Read the first file and assign the first, third, fifth, ..., nth value read (where n is an odd number) to the IntArray object; then display the content of the IntArray object.
  2. Read the second file and assign the fifth, tenth, ..., nth value read (where n is a multiple of 5) to the IntArray object; then display the content of the IntArray object.
  3. Read the third file and assign the second, fourth, sixth..., nth value read (where n is an even number) to the IntArray object; then display the content of the Int- Array object.
Use the IntArray operator[]() defined in Exercise 11.2 to store values into and read values from the IntArray object. Because operator[]() may throw an exception, use one or more try blocks and catch clauses in your program to handle the possible exceptions thrown by operator[](). Explain the reasoning behind where you located the try blocks in your program.
URL
Book: C++ Primer, Third Edition
Section: Chapter 11. Exception Handling

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: