Exceptions Handling in C++ programming



Exceptions usage

Exceptions are used to signal errors or unexpected events that occur while a program is running. Error testing is usually a straightforward process involving if statements or other control mechanisms.

For example, the following code segment will trap a division-by-zero error before it occurs:


    if (denominator == 0)
    cout << "ERROR: Cannot divide by zero.\n";
    else
    quotient = numerator / denominator;

Throwing an Exception

One way of handling complex error conditions is with exceptions. An exception is a value or an object that signals an error.

When the error occurs, an exception is said to be “thrown” because control will pass to a part of the program that catches and handles that type of error.

For example, the following code shows the divide function, modified to throw an exception when division by zero has been attempted.


    double divide(double numerator, double denominator)
    {
    if (denominator == 0)
    throw "ERROR: Cannot divide by zero.\n";
    else
    return numerator / denominator;
    }   

The following statement causes the exception to be thrown:


    throw "ERROR: Cannot divide by zero.\n";

The throw key word is followed by an argument, which can be any value. As you will see, the type of the argument is used to determine the nature of the error. The function above simply throws a string containing an error message.

Now let’s look at an entire program to see how throw, try, and catch work together.

In the following sample, valid data is given. This shows how the program should run with no errors. In the second sample run, a denominator of 0 is given. This shows the result of the exception being thrown.


    #include <iostream>
    using namespace std;
    // Function prototype
    double divide(double, double);
    int main() {
    int num1, num2;
    double quotient;
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    try {
    quotient = divide(num1, num2);
    cout << "The quotient is " << quotient << endl;
    }  
    catch (char *exceptionString) {
    cout << exceptionString;
    }
    cout << "End of the program.\n";
    return 0;
    }
    double divide(double numerator, double denominator) {
    if (denominator == 0)
    throw "ERROR: Cannot divide by zero.\n";
    else
    return numerator / denominator;
    }

    Program Output with Example Input Shown in Bold:
    Enter two numbers: 12 2
    The quotient is 6
    End of the program.

    Program Output with Example Input Shown in Bold:
    Enter two numbers: 12 0
    ERROR: Cannot divide by zero.
    End of the program.

As you can see from the second output screen, the exception caused the program to jump out of the divide function and into the catch block.

After the catch block has finished, the program resumes with the first statement after the try/catch construct.


Ads Right