Click here to Skip to main content
15,887,936 members
Articles / Programming Languages / C++
Article

Exception Handling for C++

Rate me:
Please Sign up or sign in to vote.
1.22/5 (29 votes)
31 Jan 20043 min read 64.8K   376   13   15
An article that explains the use of Exception Handling in C++ programs.

Introduction

Exception Handling is an important part of every C++ program. Without it programming is not only more difficult but more time consuming. These examples should make programming easier and faster for you.

Using the code

This article will focus on the three main keywords used in Exception Handling. They are: try, throw, and catch. Essentially the try block tries to execute a piece of code and when it fails, for whatever reason, it throws the error to catch where the catch block executes an alternate piece of code.

Only code inside the try block will be monitored for exceptions. If an exceptions cannot be thrown it will result in a program termination using exit() or abort(). For example a double won't work with an int exception. Refer to the example below.

try {
    throw 100;  //Throw an error.
}
catch (double i) { // Catch will not execute and program will terminate
    cout << "Exception caugh:  " << i << ".\n";
    getch();
}

Exception 002

Now look at a program that will work. The try block below contains multiple statements, some of the statements will execute while others may not get the chance. It is certain that everything up until if will execute, but depending on what the user inputs the program could go in two different directions. It could finish out executions the way it was designed to or the throw will be executed. If the throw is executed then the user, or the program, has done they, or it, shouldn't have.

Next note the lines of code after the else statement. This code will not execute in fact the program doesn't even notice it. Writing code after throw is the same as writing it after a goto statement.

try
{
    system("cls");
    cout << "What is the name:  ";
    cin >> gotostr;
    if(gotostr == "Scooter" || gotostr == "scooter" || gotostr == "SCOOTER")
    {
        cout << "That is the right name.\n";
        getch();
        system("cls");
        return 0;
    }
    else
    {
        throw gotostr;
        cout << "This code is useless.\n";
    }
}

Finally, catch is the last part of the three. It catches the variable that was thrown to it and will only catch that variable. It then executes the code included in its block. Catch will catch any variable that you tell it to as long as you reference it as shown below. If you throw string you must reference it as string. If you throw integer values you should reference them as integer values.

catch (string gotostr)
    {
        system("cls");
        cout << "Error, Press any key to try again.\n";
        getch();
        goto begin;
    }

Exception 003

These past examples are designed to show how try, throw, and catch work. But, they are not allways useful in a real world C++ program. However, the example below will show how exception handling can be more realisticly writen for a program. Most real world programs will include class type exceptions, so follow these examples. The first thing you have to do is make this class.

class interror
{
public:
	char str_error[80];
	int why1;

	interror() 
	{
		*str_error = 0; why1 = 0;
	}

	interror(char *e, int w)
	{
		strcpy(str_error, e);
		why1 = w;
	}

};

This is a fairly simple class that includes two variables, str_error and why1. These variables are needed to more easily handle multiple exceptions that come from the same problem. Instead of typing an exception over and over we can use this class and only type it once.

Now enter the main portion of the program.

int main()
{
	int i;
	int n;
	try
	{
		cout << "Enter a denominator:  ";  // When you run this program enter 0.
		cin >> n;
		if (n == 0)
		{
			throw interror("Cannot divide by: ", n);
		}
		else
		{
			i=100/n;
			cout << "The answer is "  << i << "\n";
		}
	}
	catch (interror e) 
	{
		cout << e.str_error << ":  ";
		cout << e.why1 << "\n";
	}

	return 0;
}

The program starts with declaring the variables i and n these are used for the formula that the program will be based on. Next the program askes for a number to be used in the denominator. After this is entered the exception handling you programmed kicks in.

After the if statement this line is used to throw the class we created.

throw interror("Cannot divide by: ", n);

The throw statement throws the class interror the statement comming after it tells the program what test it should throw with the class.(The text is the error measage) After the program throws the class and it is cought it outputs str_error, which represents the class text statement, and why1 displays the integer that was not accepted by the program, which, in this case, is 0.

This is the program output.

Enter a denominator: 0
Cannot divide by: 0
Press any key to continue.

Points of Interest

In Exception003 when you run the program and put in an integer you cannot input any integer bigger than 50. If you do the program will still run but your answer will come out to be 1, which isn't right. The program cannot support a decimal answer, however you can input a decimal integer as the denominator and the program will execute the division correctly.
return 0;

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Instructor/Trainer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionhow can handel unidentified exception handel Pin
Secrets6-Oct-04 3:29
Secrets6-Oct-04 3:29 
GeneralGood, it is just good enough! Pin
ChauJohnthan9-May-04 6:31
ChauJohnthan9-May-04 6:31 
Wish your next one!

4 points!
GeneralToo little detail Pin
KevinHall2-Feb-04 8:50
KevinHall2-Feb-04 8:50 
QuestionInaccurate?? Pin
S. Senthil Kumar1-Feb-04 23:14
S. Senthil Kumar1-Feb-04 23:14 
AnswerRe: Inaccurate?? Pin
Anonymous2-Feb-04 0:47
Anonymous2-Feb-04 0:47 
GeneralRe: Inaccurate?? Pin
S. Senthil Kumar2-Feb-04 2:10
S. Senthil Kumar2-Feb-04 2:10 
GeneralRe: Inaccurate?? Pin
WREY2-Feb-04 2:17
WREY2-Feb-04 2:17 
GeneralRe: Inaccurate?? Pin
Anonymous2-Feb-04 3:04
Anonymous2-Feb-04 3:04 
GeneralRe: Inaccurate?? Pin
WREY2-Feb-04 3:29
WREY2-Feb-04 3:29 
AnswerRe: Inaccurate?? Pin
FrankRizzo25-Feb-04 17:37
FrankRizzo25-Feb-04 17:37 
GeneralRe: Inaccurate?? Pin
S. Senthil Kumar26-Feb-04 2:32
S. Senthil Kumar26-Feb-04 2:32 
GeneralRe: Inaccurate?? Pin
FrankRizzo26-Feb-04 13:17
FrankRizzo26-Feb-04 13:17 
GeneralRe: Inaccurate?? Pin
FrankRizzo26-Feb-04 13:19
FrankRizzo26-Feb-04 13:19 
QuestionOnly comments? Pin
Claudius Mokler1-Feb-04 22:56
Claudius Mokler1-Feb-04 22:56 
AnswerRe: Only comments? Pin
Anonymous2-Feb-04 7:38
Anonymous2-Feb-04 7:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.