Click here to Skip to main content
12,999,375 members (43,985 online)
Click here to Skip to main content
Add your own
alternative version


13 bookmarked
Posted 31 Jan 2004

Exception Handling for C++

, 31 Jan 2004
Rate this:
Please Sign up or sign in to vote.
An article that explains the use of Exception Handling in C++ programs.
<!-- Add the rest of your HTML here -->


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";

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.

    cout << "What is the name:  ";
    cin >> gotostr;
    if(gotostr == "Scooter" || gotostr == "scooter" || gotostr == "SCOOTER")
        cout << "That is the right name.\n";
        return 0;
        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)
        cout << "Error, Press any key to try again.\n";
        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
	char str_error[80];
	int why1;

		*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;
		cout << "Enter a denominator:  ";  // When you run this program enter 0.
		cin >> n;
		if (n == 0)
			throw interror("Cannot divide by: ", 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;


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


About the Author

Brad Hanna
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

Questionhow can handel unidentified exception handel Pin
Secrets6-Oct-04 3:29
memberSecrets6-Oct-04 3:29 
GeneralGood, it is just good enough! Pin
ChauJohnthan9-May-04 6:31
memberChauJohnthan9-May-04 6:31 
GeneralToo little detail Pin
KevinHall2-Feb-04 8:50
memberKevinHall2-Feb-04 8:50 
QuestionInaccurate?? Pin
S. Senthil Kumar1-Feb-04 23:14
memberS. Senthil Kumar1-Feb-04 23:14 
AnswerRe: Inaccurate?? Pin
Anonymous2-Feb-04 0:47
sussAnonymous2-Feb-04 0:47 
GeneralRe: Inaccurate?? Pin
S. Senthil Kumar2-Feb-04 2:10
memberS. Senthil Kumar2-Feb-04 2:10 
GeneralRe: Inaccurate?? Pin
WREY2-Feb-04 2:17
memberWREY2-Feb-04 2:17 
GeneralRe: Inaccurate?? Pin
Anonymous2-Feb-04 3:04
sussAnonymous2-Feb-04 3:04 
GeneralRe: Inaccurate?? Pin
WREY2-Feb-04 3:29
memberWREY2-Feb-04 3:29 
AnswerRe: Inaccurate?? Pin
FrankRizzo25-Feb-04 17:37
memberFrankRizzo25-Feb-04 17:37 
GeneralRe: Inaccurate?? Pin
S. Senthil Kumar26-Feb-04 2:32
memberS. Senthil Kumar26-Feb-04 2:32 
GeneralRe: Inaccurate?? Pin
FrankRizzo26-Feb-04 13:17
memberFrankRizzo26-Feb-04 13:17 
GeneralRe: Inaccurate?? Pin
FrankRizzo26-Feb-04 13:19
memberFrankRizzo26-Feb-04 13:19 
QuestionOnly comments? Pin
Claudius Mokler1-Feb-04 22:56
memberClaudius Mokler1-Feb-04 22:56 
AnswerRe: Only comments? Pin
Anonymous2-Feb-04 7:38
sussAnonymous2-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170622.1 | Last Updated 1 Feb 2004
Article Copyright 2004 by Brad Hanna
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid