What Are Exception Mechanisms in C++? - dummies

What Are Exception Mechanisms in C++?

By Stephen R. Davis

Occasionally functions don′t work properly — even for seasoned C++ programmers. The traditional means of reporting failure is to return some indication to the caller. C++ includes a mechanism for capturing and handling errors called exceptions. The handling of error conditions with exceptions is a key concept to understand.

The exception mechanism is based on the keywords try, catch, and throw (that′s right, more variable names that you can′t use). In outline, it works like this: A function tries to get through a piece of code. If the code detects a problem, it throws an error indication that the calling function must catch.

The following code snippet demonstrates how that works in 1s and 0s:

//  FactorialException - demonstrate exceptions using
//                       a factorial function
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
// factorial - compute factorial
int factorial(int n)
    // you can't handle negative values of n;
    // better check for that condition first
    if (n < 0)
        throw string("Argument for factorial negative");
    // go ahead and calculate factorial
    int accum = 1;
    while(n > 0)
        accum *= n;
    return accum;
int main(int nNumberofArgs, char* pszArgs[])
        // this will work
        cout << "Factorial of 3 is "
             << factorial(3) << endl;
        // this will generate an exception
        cout << "Factorial of -1 is "
             << factorial(-1) << endl;
        // control will never get here
        cout << "Factorial of 5 is "
             << factorial(5) << endl;
    // control passes here
    catch(string error)
        cout << "Error occurred: " << error << endl;
        cout << "Default catch " << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    return 0;

main() starts out by creating a block outfitted with the try keyword. Within this block, it can proceed the way it would if the block were not present. In this case, main() attempts to calculate the factorial of a negative number.

Not to be hoodwinked, the clever factorial() function detects the bogus request and throws an error indication using the throw keyword. Control passes to the catch phrase, which immediately follows the closing brace of the try block. The third call to factorial() is not performed.

Through a not-so-clever feature called an exception specification, you can add the type of objects that factorial() throws to its declaration. At one time, someone thought this would be a good idea, but times change. Exception specifications were never mandatory and have been deprecated in the 2011 standard.