Exception Handling


Foundations of Exceptions

 

Introduction

During the execution of a program, the computer will face two types of situations: those it is prepared to deal with and those it doesn’t like. Imagine you write a program that asks the user to supply two numbers to perform a calculation.
 

Practical Learning: Introduction to Exceptions

  1. Create a new Console Application using the Console Wizard
  2. To save the project, on the Standard toolbar, click the Save All button.
  3. Create a new folder named Exceptions1 and display it in the Save In combo box.
  4. Save the unit as Exercise
  5. Save the project as Exceptions
  6. Change the content of the file with the following:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    int main(int argc, char* argv[])
    {
        double a, b, c;
    
        // Request two numbers from the user
        cout << "Please provide two numbers\n";
        cout << "First Number:  ";
        cin >> a;
        cout << "Second Number: ";
        cin >> b;
    
        // Multiply the numbers and display the result
        c = a * b;
        cout << "\n" << a << " * " << b << " = " << c;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  7. To test the program, press F9.
  8. After testing the program, return to Bcb.

This is a classic easy program. When it comes up, the user is asked to simply type two numbers; the program would use them to perform a multiplication and display the result.

Imagine that a user, thanks to his infinite creativity or because of just a mistake, decides to type the name of a country or somebody’s telephone number as one of the requested values. Since a program such as this one is not prepared to multiply two strings or one number to a string, it would not know what to do. The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. What actually happens is that, whenever the compiler is handed a task, it would try to perform the assignment. If it can’t perform the assignment, for any reason it is not prepared for, it would throw an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can catch the error yourself and deal with it by telling the compiler what to do when this type of error occurs.

 

Exceptional Behaviors

An exception is a situation that would be unusual for the program that is being processed. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. An error result or an unpredictable behavior on your program not caused by the operating system is called an exception. The ability to deal with a program’s eventual abnormal behavior is called exception handling. C++ provides three keywords to handle an exception.

  1. Trying the normal flow: To deal with the expected behavior of a program, use the try keyword as in the following syntax:

    try {Behavior}

    The try keyword is required. It lets the compiler know that you are anticipating an abnormal behavior and will try to deal with it. The actual behavior that needs to be evaluated is included between an opening curly bracket “{“ and a closing curly bracket “}”. Inside of the brackets, implement the normal flow that the program should follow, at least for this section of the code.
  2. Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the program crash or instead of letting the compiler send the error to the operating system, you can transfer the flow of the program to another section that can deal with it. The syntax used by this section is:

    catch(Argument) {WhatToDo}

    This section always follows the try section and there must not be any code between the try’s closing bracket and the catch section. The catch keyword is required and follows the try section. The catch behaves a little like a function. It uses an argument that is passed by the previous try section. The argument can be a regular variable or a class. If there is no argument to pass, the catch must at least take a three-period argument as in catch(…). The behavior of the catch clause starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. The inside of the brackets is called the body of the catch clause. Therefore, use the body of the catch to deal with the error that was caused.

    Combined with the try block, the syntax of an exception would be:
     

    try {
    	// Try the program flow
    }
    catch(Argument)
    {
    	// Catch the exception
    }
  3. Throwing an error: There are two main ways an abnormal program behavior is transferred from the try block to the catch clause. This transfer is actually carried by the throw keyword. Unlike the try and catch blocks, the throw keyword is independent of a formal syntax but still follows some rules.

 

 

Facing an Exception

An exception is a behavior that should not occur in your program but is likely to show up. The simplest exception looks like a conditional statement and here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    int StudentAge;

    cout << "Student Age: ";
    cin >> StudentAge;

    try {
        if(StudentAge < 0)
            throw;
        cout << "\nStudent Age: " << StudentAge;
    }
    catch(...)
    {
    }
    
    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

If you run this program and type a positive integer for the student’s age, the program would respond by displaying the student age. That’s a good outcome. If you run the program and type a letter or any character, the compiler would display the student age as 0. This is the first proof that the compilers are already configured to deal with some abnormal behavior of a program.

When the throw keyword is written by itself, it is a way of asking the compiler to send the exception to another handler. In fact, if there is no other handler written by you, the processing would be handed to the operating system. In this case, if you run the program and type a negative integer, since the program is not prepared to handle the exception itself, because of the presence of a single throw, the operating system would take over and display its own message. This would be “abnormal program termination” on a Microsoft Windows operating system.

 

Practical Learning: Throwing an Exception

  1. To throw our first exception, change the program as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    int main(int argc, char* argv[])
    {
        double Number1, Number2, Result;
    
        // Request two numbers from the user
        cout << "Please provide two numbers\n";
    
        try {
    	cout << "First Number: ";
    	cin >> Number1;
    	cout << "Second Number: ";
    	cin >> Number2;
    
    	if( Number2 == 0 )
    		throw;
    
    	// Perform a division and display the result
    	Result = Number1 / Number2;
    	cout << "\n" << Number1 << " / " << Number2 << " = " << Result;
        }
        catch(...)
        {
        }
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. To test the program, press F9. Test it with two non-zero numbers such as 126.45 and 5.52
  3. Return to your programming environment and test the program again. This time, type 0 for the second number.
  4. Return to Bcb.

Predicting Exceptions

 

Writing Local Exceptions

Imagine you write a program that requests a student’s age from the user. As we know, everybody’s age is positive. Therefore, we need to figure out what to do if the user types a negative number. The expression that checks whether the number entered is positive can be written as:

if(StudentAge < 0)

If the condition is true, the minimum you can do is to send the produced error away. This is done with the throw keyword:

try {
	if(StudentAge < 0)
		throw;
}

Whenever an exception occurs, and whenever you use the try keyword to try an expression, you must transfer control to a catch block. This is where you should display your own message for the error. Here is an example:

#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
	int StudentAge;

	try {
		cout << "Student Age: ";
		cin >> StudentAge;

		if(StudentAge < 0)
			throw "Positive Number Required";
		cout << "\nStudent Age: " << StudentAge;
	}
	catch(const char* Message)
	{
		cout << "Error: " << Message;
	}

	cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This program starts with the try block that asks the user to enter a positive number. If the user enters an invalid value, the program examines the throw keyword. This throw appears to display a string. The compiler registers this string and since there was an exception, the program exits the try block and looks for the first catch block it can find. If it finds a catch that doesn’t take an argument, it would still use the catch. Otherwise, you can use the catch block to display the error string that was sent by the throw keyword. In the example above, the catch uses a string as a pseudo-argument and displays it using a cout extractor.

In the example above, the catch block is configured to display a string. Let’s consider the classic division by zero operation. The division by zero is dealt with at different levels. The processor (Intel, AMD, etc) is configured not to allow it. The operating system is also prepared for it. Finally, the compiler has its own interpretation of this operation. Nevertheless, if you suspect it to occur in your program, you can take appropriate measures. When preparing to deal with division by zero, the main idea is to compare the denominator with 0. This comparison should be performed in a try block. If the comparison renders true, you should avoid the operation and hand the error (exception) to a catch. The catch is usually used to display a message as in the last code. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    double Operand1, Operand2, Result;

	// Request two numbers from the user
	cout << "This program allows you to perform a division of two numbers\n";
	cout << "To proceed, enter two numbers\n";

	try {
		cout << "First Number: ";
		cin >> Operand1;
		cout << "Second Number: ";
		cin >> Operand2;

		// Find out if the denominator is 0
		if( Operand2 == 0 )
			throw "Division by zero not allowed";

		// Perform a division and display the result
		Result = Operand1 / Operand2;
		cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result;
	}
	catch(const char* Str) // Catch an exception
	{
		// Display a string message accordingly
		cout << "\nBad Operator: " << Str;
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

The catch clause can use any type of variable as long as you configure it accordingly. Instead of a string as we have seen, you can send it an integer, then display an error depending on the integer that was sent.
 

Practical Learning: Catching an Exception

  1. To see an example where the catch receives an error in the form of an integer, change the file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    int main(int argc, char* argv[])
    {
    	double Operand1, Operand2, Result;
    
    	// Request two numbers from the user
    	cout << "This program allows you to perform a division of two numbers\n";
    	cout << "To proceed, enter two numbers\n";
    
    	try {
    		cout << "First Number: ";
    		cin >> Operand1;
    		cout << "Second Number: ";
    		cin >> Operand2;
    
    		// Find out if the denominator is 0
    		if( Operand2 == 0 )
    			throw 0;
    
    		// Perform a division and display the result
    		Result = Operand1 / Operand2;
    		cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result;
    	}
    	catch(const int n) // Catch an exception
    	{
    		// Display a string message accordingly
    		cout << "\nBad Operator: Division by " << n << " not allowed";
    	}
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program and return to Bcb.

Catching Multiple Exceptions

The exceptions as we have seen so far dealt with a single exception in a program. Most of the time, a typical program will throw different types of errors. The C++ language allows you to include different catch blocks. Each catch block can face a specific error. The syntax used is:

try {
	Code to Try
}
catch(Arg1)
{
	One Exception
}
catch(Arg2)
{
	Another Exception
}

The compiler would proceed in a top-down:

  1. Following the normal flow control of the program, the compiler enters the try block.
  2. If no exception occurs in the try block, the rest of the try block is executed.
    If an exception occurs in the try block, the try displays a throw that specifies the type of error that happened.
    1. The compiler gets out of the try and examines the first catch
    2. If the first catch doesn’t match the thrown error, the compiler proceeds with the next catch. This continues until the compiler finds a catch that matches the thrown error.
    3. If one of the catches matches the thrown error, its body executes. If no catch matches the thrown error, you have (or the compiler has) two alternatives. If there is no catches that matches the error (which means that you didn’t provide a matching catch), the compiler hands the program flow to the operating system (which calls the terminate() function). Another alternative is to include a catch whose argument is three periods: catch(…). The catch(…) is used if no other catch, provided there was another, matches the thrown error. The catch(…), if included as part of a catch clause, must always be the last catch, unless it is the only catch of the clause.

Multiple catches are written if or when a try block is expected to throw different types of errors. Imagine a program that requests some numbers from the user and performs some operation on the numbers. Such a program can be written as follows:
 

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
	double Operand1, Operand2, Result;
	char Operator;

	cout << "This program allows you to perform an operation on two numbers\n";
	cout << "To proceed, enter a number, an operator, and a number:\n";
	cin >> Operand1 >> Operator >> Operand2;

	switch(Operator)
	{
	case '+':
		Result = Operand1 + Operand2;
		break;

	case '-':
		Result = Operand1 - Operand2;
		break;

	case '*':
		Result = Operand1 * Operand2;
		break;

	case '/':
		Result = Operand1 / Operand2;
		break;

	default:
		cout << "Bad Operation";
	}

	cout << "\n" << Operand1 << " " << Operator << " "
		 << Operand2 << " = " << Result;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This program works fine as long as the user types a valid sequence of values made of a number followed by a valid arithmetic operator, followed by a number. Anything else, such an invalid number, an unexpected operator, or a wrong sequence (such as Number Number Operator), would produce an unpredictable outcome. Obviously various bad things could happen when this program is running. To handle the exceptions that this program could produce, you can start with the most likely problem that would occur. Trusting that a user is able to provide the two numbers that are requested, it is possible that a user would type an invalid operator. For example, for this program we will perform only the addition (+), the subtraction(-), the multiplication(*), and the division(/). Therefore, we will first validate the operator. This can be done as follows:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
	double Operand1, Operand2, Result;
	char Operator;

	cout << "This program allows you to perform an operation on two numbers\n";

	try {
		cout << "To proceed, enter a number, an operator, and a number:\n";
		cin >> Operand1 >> Operator >> Operand2;

		if(Operator != '+' && Operator != '-' &&
		   Operator != '*' && Operator != '/')
			throw Operator;

		switch(Operator)
		{
		case '+':
			Result = Operand1 + Operand2;
			break;

		case '-':
			Result = Operand1 - Operand2;
			break;

		case '*':
			Result = Operand1 * Operand2;
			break;

		case '/':
			Result = Operand1 / Operand2;
			break;
		}

		cout << "\n" << Operand1 << " " << Operator << " "
			 << Operand2 << " = " << Result;
	}
	catch(const char n)
	{
		cout << "\nOperation Error: " << n << " is not a valid operator";
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

When this program runs, if the user provides two valid numbers but a wrong operator, the program asks a throw to send a character (in fact the character that was typed as the operator) that represents the error. Then, when the compiler gets out of the try block, it looks for and finds a catch clause that receives a character value. Therefore, this catch is executed.
 

Practical Learning: Catching an Exception

  1. Imagine that the user wants to perform a division. You need to tell the compiler what to do if the user enters the denominator as 0 (or 0.00). If this happens, the best option, and probably the only one you should consider is to display a message and get out. To implement this behavior, we will add another catch block that displays a message. As an example, change the program as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    int main(int argc, char* argv[])
    {
        double Operand1, Operand2, Result;
    	char Operator;
    
    	// Request two numbers from the user
    	cout << "This program allows you to perform an operation of two numbers\n";
    	cout << "To proceed, enter two numbers\n";
    
    	try {
    		cout << "First Number:  ";
    		cin >> Operand1;
    		cout << "Operator:      ";
    		cin >> Operator;
    		cout << "Second Number: ";
    		cin >> Operand2;
    
    		// Make sure the user typed a valid operator
    		if(Operator != '+' && Operator != '-' &&
    		   Operator != '*' && Operator != '/')
    			throw Operator;
    
    		// Find out if the denominator is 0
    		if(Operator == '/')
    			if(Operand2 == 0)
    				throw 0;
    
    		// Perform an operation based on the user's choice
    		switch(Operator)
    		{
    		case '+':
    			Result = Operand1 + Operand2;
    			break;
    
    		case '-':
    			Result = Operand1 - Operand2;
    			break;
    
    		case '*':
    			Result = Operand1 * Operand2;
    			break;
    
    		case '/':
    			Result = Operand1 / Operand2;
    			break;
    		}
    
    		// Display the result of the operation
    		cout << "\n" << Operand1 << " " << Operator << " "
    		     << Operand2 << " = " << Result << "\n\n";
    	}
    	catch(const char n)
    	{
    		cout << "\nOperation Error: " << n << " is not a valid operator";
    	}
    	catch(const int p)
    	{
    		cout << "\nBad Operation: Division by " << p << " not allowed";
    	}
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Test the program and return to Bcb.

    When running this program, if the user types a wrong operator, the compiler considers the integer error, gets out f the try block, and looks for a catch that can use a character. The first catch can validate it and gets executed. If the user enters the right values (Number Operator Number), then the compiler finds out if the operator entered was a forward slash “/” used to perform a division. If the user wants to perform a division, the compiler finds out if the second operand, the denominator, is 0. If it is, the program presents a throw that sends an integer. Based on this exception, the compiler gets out of the try block and starts looking for a catch block that can use an integer. The first catch can’t, it uses a character. Therefore, the compiler looks at the next catch, if any. Our program provides a second catch that takes an integer as an argument. Therefore, this catch gets executed.

    Not all our problems are solved. Image the user types an invalid number. The first characteristic of an invalid number is one that contains anything else than a digit (a character between 0 and 9). Since our program performs its operations on decimal numbers, we need to allow the number to have a decimal portion. Instead of expecting numeric values from the user, we will request arrays of characters. We will use the isdigit() function to examine each character entered in order to find out whether any one of them is not a digit. Also, we will allow the user to type a period that separates the decimal part of a number. If any of the characters that the user entered is not a digit, we will throw a string error so a catch can deal with it. This means that we will add a catch that is different from the other already existing ones.

    So far, we were requesting two double-precision numbers from the user. In order to check each number and validate it, instead of decimals, we will ask the user to type two strings (arrays of characters).

    Therefore, change the program as follows:

    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    int main(int argc, char* argv[])
    {
        char Number1[40], Number2[40];
    	double Operand1, Operand2, Result;
    	char Operator;
    
    	// Request two numbers from the user
    	cout << "This program allows you to perform a division of two numbers\n";
    	cout << "To proceed, enter two numbers\n";
    
    	try {
    		cout << "First Number:  ";
    		cin >> Number1;
    		cout << "Operator:      ";
    		cin >> Operator;
    		cout << "Second Number: ";
    		cin >> Number2;
    
    		// Examine each character of the first operand
    		// to find out if the user included a non-digit in the number
    		for(int i = 0; i < strlen(Number1); i++)
    		    if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period
    			    throw Number1;// Send the error as a string
    
    		Operand1 = atof(Number1);
    
    		// Do the same for the second number entered
    		for(int j = 0; j < strlen(Number1); j++)
    		    if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period
    			    throw Number2;// Send the error as a string
    
    		Operand2 = atof(Number2);
    
    		// Make sure the user typed a valid operator
    		if(Operator != '+' && Operator != '-' &&
    		   Operator != '*' && Operator != '/')
    			throw Operator;
    
    		// Find out if the denominator is 0
    		if(Operator == '/')
    			if(Operand2 == 0)
    				throw 0;
    
    		// Perform an operation based on the user's choice
    		switch(Operator)
    		{
    		case '+':
    			Result = Operand1 + Operand2;
    			break;
    
    		case '-':
    			Result = Operand1 - Operand2;
    			break;
    
    		case '*':
    			Result = Operand1 * Operand2;
    			break;
    
    		case '/':
    			Result = Operand1 / Operand2;
    			break;
    		}
    
    		// Display the result of the operation
    		cout << "\n" << Operand1 << " " << Operator << " "
    		     << Operand2 << " = " << Result << "\n\n";
    	}
    	catch(const int n)
    	{
    		cout << "\nBad Operation: Division by " << n << " not allowed";
    	}
    	catch(const char n)
    	{
    		cout << "\nOperation Error: " << n << " is not a valid operator";
    	}
    	catch(const char *BadOperand)
    	{
    		cout << "\nError: " << BadOperand << " is not a valid number";
    	}
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  3. Test the program and return to your programming environment.

Nesting Exceptions

The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation. The compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also asked the compiler to check that valid numbers were entered. Even these two criteria are met, it was possible that the user enter 0 for the denominator. The block that is used to check for a non-zero denominator depends on the exception that validates the operators. In other words, before we check the value of the denominator, we have first made sure that a valid number (a string that contains only digits and a period) was entered for the denominator. For this reason, the exception that could result from a zero denominator depends on the user first entering a valid number for the denominator.

C++ allows you to nest exceptions, using the same techniques we applied to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es). To effectively handle the exception, make sure you include an appropriate throw in the try block. Here is an exception:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
	char Number1[40], Number2[40];
	double Operand1, Operand2, Result;
	char Operator;

	cout << "This program allows you to perform an operation on two numbers\n";

	try {
		cout << "To proceed, enter\n";
		cout << "First Number: "; cin >> Number1;
		cout << "An Operator: "; cin >> Operator;
		cout << "Second Number: "; cin >> Number2;

		// Examine each character of the first operand
		// to find out if the user included a non-digit in the number
		for(int i = 0; i < strlen(Number1); i++)
		    if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period
			    throw Number1; // Send the error as a character

		Operand1 = atof(Number1);

		// Do the same for the second number entered
		for(int j = 0; j < strlen(Number2); j++)
		    if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period
			throw Number2;//[j]; // Send the error as a character

		Operand2 = atof(Number2);

		if(Operator != '+' && Operator != '-' &&
		   Operator != '*' && Operator != '/')
			throw Operator;

		switch(Operator)
		{
		case '+':
			Result = Operand1 + Operand2;
			cout << "\n" << Operand1 << " + "
				 << Operand2 << " = " << Result;
			break;

		case '-':
			Result = Operand1 - Operand2;
			cout << "\n" << Operand1 << " - "
				 << Operand2 << " = " << Result;
			break;

		case '*':
			Result = Operand1 * Operand2;
			cout << "\n" << Operand1 << " * "
				 << Operand2 << " = " << Result;
			break;

		case '/':
			// The following exception is nested in the previous try
			try {
				if(Operand2 == 0)
					throw "Division by 0 not allowed";
				
				Result = Operand1 / Operand2;
				cout << "\n" << Operand1 << " / "
					 << Operand2 << " = " << Result;
			}
			catch(const char * Str)
			{
				cout << "\nBad Operation: " << Str;
			}
			break;
		}
	}
	catch(const char n)
	{
		cout << "\nOperation Error: " << n << " is not a valid operator";
	}
	catch(const char *BadOperand)
	{
		cout << "\nError: " << BadOperand << " is not a valid number";
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Exceptions and Functions

One of the most effective techniques used to deal with code is to isolate assignments. We have learned this when studying functions. For example, the switch statement that was performing the operations in the “normal” version of our program can be written as follows:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
	double Operand1, Operand2, Result;
	char Operator;
	double __fastcall Calculator(const double N1,
                                 const double N2, const char p);

	cout << "This program allows you to perform a division of two numbers\n";
	cout << "To proceed, enter a number, an operator, and a number:\n";
	cin >> Operand1 >> Operator >> Operand2;

	Result = Calculator(Operand1, Operand2, Operator);

	cout << "\n" << Operand1 << " " << Operator << " "
		 << Operand2 << " = " << Result;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
double __fastcall Calculator(const double Oper1,
                             const double Oper2, const char Symbol)
{
	double Value;

	switch(Symbol)
	{
	case '+':
		Value = Oper1 + Oper2;
		break;

	case '-':
		Value = Oper1 - Oper2;
		break;

	case '*':
		Value = Oper1 * Oper2;
		break;

	case '/':
		Value = Oper1 / Oper2;
		break;
	}

	return Value;
}
//---------------------------------------------------------------------------

You can still use regular functions along with functions that handle exceptions. Here is an example:

int main(int argc, char* argv[])
{
    char Number1[40], Number2[40];
	double Operand1, Operand2, Result;
	char Operator;

	cout << "This program allows you to perform an operation on two numbers\n";

	try {
		cout << "To proceed, enter\n";
		cout << "First Number: "; cin >> Number1;
		cout << "An Operator: "; cin >> Operator;
		cout << "Second Number: "; cin >> Number2;

		// Examine each character of the first operand
		// to find out if the user included a non-digit in the number
		for(int i = 0; i < strlen(Number1); i++)
		    if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period
			throw Number1; // Send the error as a character

		Operand1 = atof(Number1);

		// Do the same for the second number entered
		for(int j = 0; j < strlen(Number2); j++)
		    if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period
			throw Number2;//[j]; // Send the error as a character

		Operand2 = atof(Number2);

		if(Operator != '+' && Operator != '-' &&
		   Operator != '*' && Operator != '/')
			throw Operator;

		if(Operator == '/')
		    if(Operand2 == 0)
			throw 0;

		Result = Calculator(Operand1, Operand2, Operator);
		cout << "\n" << Operand1 << " " << Operator << " "
		     << Operand2 << " = " << Result;
	}
	catch(const int n)
	{
		cout << "\nBad Operation: Division by " << n << " not allowed";
	}
	catch(const char n)
	{
		cout << "\nOperation Error: " << n << " is not a valid operator";
	}
	catch(const char *BadOperand)
	{
		cout << "\nError: " << BadOperand << " is not a valid number";
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
double __fastcall Calculator(const double Oper1,
                             const double Oper2, const char Symbol)
{
	double Value;

	switch(Symbol)
	{
	case '+':
		Value = Oper1 + Oper2;
		break;

	case '-':
		Value = Oper1 - Oper2;
		break;

	case '*':
		Value = Oper1 * Oper2;
		break;

	case '/':
		Value = Oper1 / Oper2;
		break;
	}

	return Value;
}
//---------------------------------------------------------------------------

As done in the main() function, any member function of a program can take care of its own exceptions that would occur in its body. Here is an example of an exception handled in a function:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
void __fastcall Calculator(const double m, const double n, const char p);

int main(int argc, char* argv[])
{
    char Number1[40], Number2[40];
	double Operand1, Operand2;
	char Operator;

	cout << "This program allows you to perform an operation on two numbers\n";

	try {
		cout << "To proceed, enter\n";
		cout << "First Number: "; cin >> Number1;
		cout << "An Operator: "; cin >> Operator;
		cout << "Second Number: "; cin >> Number2;

		// Examine each character of the first operand
		// to find out if the user included a non-digit in the number
		for(int i = 0; i < strlen(Number1); i++)
		    if( (!isdigit(Number1[i])) && (Number1[i] != '.') )
       			throw Number1; // Send the error as a character

		Operand1 = atof(Number1);

		// Do the same for the second number entered
		for(int j = 0; j < strlen(Number2); j++)
		    if( (!isdigit(Number2[j])) && (Number2[j] != '.') )
			throw Number2; // Send the error as a character

		Operand2 = atof(Number2);

		if(Operator != '+' && Operator != '-' &&
		   Operator != '*' && Operator != '/')
			throw Operator;

		Calculator(Operand1, Operand2, Operator);
	}
	catch(const char n)
	{
		cout << "\nOperation Error: " << n << " is not a valid operator";
	}
	catch(const char *BadOperand)
	{
		cout << "\nError: " << BadOperand << " is not a valid number";
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall Calculator(const double Oper1,
                             const double Oper2, const char Symbol)
{
	double Value;

	switch(Symbol)
	{
	case '+':
		Value = Oper1 + Oper2;
		cout << "\n" << Oper1 << " + "
			 << Oper2 << " = " << Value;
		break;

	case '-':
		Value = Oper1 - Oper2;
		cout << "\n" << Oper1 << " - "
			 << Oper2 << " = " << Value;
		break;

	case '*':
		Value = Oper1 * Oper2;
		cout << "\n" << Oper1 << " * "
			 << Oper2 << " = " << Value;
		break;

	case '/':
		// The following try exception is nested in the previous try
		try {
			if(Oper2 == 0)
				throw "Division by 0 not allowed";

			Value = Oper1 / Oper2;
			cout << "\n" << Oper1 << " / "
				 << Oper2 << " = " << Value;
		}
		catch(const char * Str)
		{
			cout << "\nBad Operation: " << Str;
		}
		break;
	}
}
//---------------------------------------------------------------------------

Isolating assignments and handing them to functions is a complete and important matter in the area of application programming. Consider a program that handles a simple exception such as this one:
 

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
    double Operand1, Operand2, Result;
	char Operator = '/';

	cout << "This program allows you to perform a division of two numbers\n";

	try {
		cout << "To proceed, enter two numbers: ";
		cin >> Operand1 >> Operand2;

		if( Operand2 == 0 )
			throw "Division by zero not allowed";

		Result = Operand1 / Operand2;
		cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result;
	}
	catch(const char* Str)
	{
		cout << "\nBad Operator: " << Str;
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

One of the ways you can use functions in exception routines is to have a central function that receives variables, sends them to an external function. The external function tests the value of a variable. If an exception occurs, the external function displays or sends a throw. This throw can be picked up by the function that sent the variable. If the throw carries a value such as an integer or a string, the function that originated the try can hand it to a catch or one of its catches to handle the exception. Observe the following example that implements this scenario:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
void __fastcall Division(const double a, const double b);

int main(int argc, char* argv[])
{
    double Operand1, Operand2;

	cout << "This program allows you to perform a division of two numbers\n";

	// Start an exception 
	try {
		cout << "To proceed, enter two numbers: ";
		cin >> Operand1 >> Operand2;

		// Pass the new values to a function that will analyze them
		Division(Operand1, Operand2);
	}
	catch(const char* Str)
	{
		cout << "\nBad Operator: " << Str;
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall Division(const double a, const double b)
{
	double Result;

	// If an exception occurred,
	if( b == 0 ) // then throw a string to the function caller
		throw "Division by zero not allowed";

	Result = a / b;
	cout << "\n" << a << " / " << b << " = " << Result;
}
//---------------------------------------------------------------------------

In this program, the Division function receives two values that it is asked to perform and division with. The Division function analyzes the second argument that represents the denominator. If this argument is zero, an exception is fund and the Division functions throws a string back to the function that sent the arguments.
C++ (as described in the C++ Standards), allows you to specify that a function is an exception carrier. If you write a function that carries an exception, you can type the throw keyword followed by parentheses on the right side of the function. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
void __fastcall Division(const double a, const double b);

int main(int argc, char* argv[])
{
	double Operand1, Operand2;

	cout << "This program allows you to perform a division of two numbers\n";

	// Start an exception 
	try {
		cout << "To proceed, enter two numbers: ";
		cin >> Operand1 >> Operand2;

		// Pass the new values to a function that will analyze them
		Division(Operand1, Operand2);
	}
	catch(const char* Str)
	{
		cout << "\nBad Operator: " << Str;
	}

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall Division(const double a, const double b)
{
	double Result;

	// If an exception occurred,
	if( b == 0 ) // then throw a string to the function caller
		throw;

	Result = a / b;
	cout << "\n" << a << " / " << b << " = " << Result;
}
//---------------------------------------------------------------------------

As if it were a function, the throw keyword used like this can have parentheses. If it doesn’t take any argument, the parentheses can be left empty as in the last example. If the function that is called from a try block will throw a specific type of exception, you can write the exception message in the parentheses of the throw. Here is an example:

//---------------------------------------------------------------------------
void __fastcall Calculator(const double Oper1, const double Oper2,
		const char Symbol)
{
	double Value;

	switch(Symbol)
	{
	case '+':
		Value = Oper1 + Oper2;
		cout << "\n" << Oper1 << " + "
			 << Oper2 << " = " << Value;
		break;
	
	case '-':
		Value = Oper1 - Oper2;
		cout << "\n" << Oper1 << " - "
			 << Oper2 << " = " << Value;
		break;

	case '*':
		Value = Oper1 * Oper2;
		cout << "\n" << Oper1 << " * "
			 << Oper2 << " = " << Value;
		break;

	case '/':
		if(Oper2 == 0)
			throw("Division by 0 not allowed");

		Value = Oper1 / Oper2;
		cout << "\n" << Oper1 << " / "
			 << Oper2 << " = " << Value;
		break;
	}
}
//---------------------------------------------------------------------------

A function can also be called to perform more than one test to eventually throw more than one exception. Such a function can (and should) be programmed to throw different types of exceptions. Here is an example of such a function:

//---------------------------------------------------------------------------
double __fastcall Calculator(const double Oper1,
                             const double Oper2, const char Symbol)
{
	double Value;

	if(Symbol != '+' && Symbol != '-' &&
	   Symbol != '*' && Symbol != '/')
		throw Symbol;

	switch(Symbol)
	{
	case '+':
		Value = Oper1 + Oper2;
		cout << "\n" << Oper1 << " + "
			 << Oper2 << " = " << Value;
		break;

	case '-':
		Value = Oper1 - Oper2;
		cout << "\n" << Oper1 << " - "
			 << Oper2 << " = " << Value;
		break;

	case '*':
		Value = Oper1 * Oper2;
		cout << "\n" << Oper1 << " * "
			 << Oper2 << " = " << Value;
		break;

	case '/':
		if(Oper2 == 0)
			throw("Division by 0 not allowed");

		Value = Oper1 / Oper2;
		cout << "\n" << Oper1 << " / "
		     << Oper2 << " = " << Value;
		break;
	}

	return Value;
}
//---------------------------------------------------------------------------

As you can see, this function throws two different types of exceptions: a character and a string. When writing such a function that throws, but doesn’t handle, different exceptions, you can make sure this function throws different types of exceptions. Here is the reason. When a function throws an exception, it only sometimes specifies the type of exception. It doesn’t specify where the exception is going. When the function that called this function receives the thrown type, it must figure out what block must catch the throw. If this function (the function that was called) throws various exceptions of the same type, the calling function would send all of them to the same catch, which can create a confusion of its own. This type of confusion is the kind that compiles the program without any problem but can display an unpredictable result. On the other hand, if the called function throws different types of exceptions, the calling function, when it receives the throws, can send each to the appropriate catch that would handle it.

Obviating the Throwing of Exceptions

When you have a function that is configured to throw an exception, you can show it in its declaration. To show that a function is throwing an exception, on the right side of the function, after its closing parentheses, you can type the throw keyword followed by parentheses. Inside of the throw parentheses, you can type the kind of exception that the function is throwing. Here is an example:

//---------------------------------------------------------------------------
double __fastcall Validate(const char* N) throw(const char*)
{
	double Valid;

	for(int i = 0; i < strlen(N); i++)
		if( (!isdigit(N[i])) && (N[i] != '.') )
			throw N;

	Valid = atof(N);
	return Valid;
}
//---------------------------------------------------------------------------

If a function is throwing more than one exception, inside of the parentheses of the throw, type the different types of arguments. Unlike a function, the order of arguments is not important because each will be treated separately and dealt with on its own. Such a function can be declared as followed:

void __fastcall Calculator(const double m, const double n, const char p) throw(const char*, const char);

Here are two function functions that throw exceptions, one of them throws one exception while the other throws two:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
void __fastcall Calculator(const double m, const double n,
				  const char p) throw(const char*, const char);
double __fastcall Validate(const char *N) throw(const char*);
//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    char Number1[40], Number2[40];
	double Operand1, Operand2;
	char Operator;

	cout << "This program allows you to perform an operation on two numbers\n";

	try {
		cout << "To proceed, enter\n";
		cout << "First Number: "; cin >> Number1;
		cout << "An Operator: "; cin >> Operator;
		cout << "Second Number: "; cin >> Number2;

		Operand1 = Validate(Number1);
		Operand2 = Validate(Number2);

		try {
			Calculator(Operand1, Operand2, Operator);
		}
		catch(const char * Str)
		{
			cout << "\nBad Operation: " << Str;
		}
	}
	catch(const char n)
	{
		cout << "\nOperation Error: " << n << " is not a valid operator";
	}
	catch(const char *BadOperand)
	{
		cout << "\nError: " << BadOperand << " is not a valid number";
	}

    cout << "\n\nPress any key to continue...";
    getch();
    getch();
    return 0;
}
//---------------------------------------------------------------------------
void __fastcall Calculator(const double Oper1, const double Oper2,
                const char Symbol) throw(const char*, const char)
{
	double Value;

	if(Symbol != '+' && Symbol != '-' &&
	   Symbol != '*' && Symbol != '/')
		throw Symbol;

	switch(Symbol)
	{
	case '+':
		Value = Oper1 + Oper2;
		cout << "\n" << Oper1 << " + "
			 << Oper2 << " = " << Value;
		break;

	case '-':
		Value = Oper1 - Oper2;
		cout << "\n" << Oper1 << " - "
			 << Oper2 << " = " << Value;
		break;

	case '*':
		Value = Oper1 * Oper2;
		cout << "\n" << Oper1 << " * "
			 << Oper2 << " = " << Value;
		break;

	case '/':
		if(Oper2 == 0)
			throw("Division by 0 not allowed");
		Value = Oper1 / Oper2;
		cout << "\n" << Oper1 << " / "
			 << Oper2 << " = " << Value;
		break;
	}
}
//---------------------------------------------------------------------------
double __fastcall Validate(const char* N) throw(const char*)
{
	double Valid;

	for(unsigned int i = 0; i < strlen(N); i++)
		if( (!isdigit(N[i])) && (N[i] != '.') )
			throw N;

	Valid = atof(N);
	return Valid;
}
//---------------------------------------------------------------------------

Practical Learning: Obviating Throwing Functions

  1. As  as follows:
     
    
                  
  2. In the C++ source file, change the functions as follows:
     
    
                  
  3. Test the program and return to Bcb.

 

 

Previous Copyright © 2003 FunctionX, Inc. Next