- Throwing an Exception
- The Try Block
- Catching an Exception
- Exception Specifications
- Exceptions and Design Issues
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.