Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Exception Handling in C++

In this article we will see some techniques of exception handling in C++.

Introduction to Exception Handling

Exceptions are anomalies that occur during the normal flow of a program and prevent it from continuing. These anomalies--user, logic, or system errors--can be detected by a function. If the detecting function cannot deal with the anomaly, it "throws" an exception. A function that "handles" that kind of exception catches it.

In C++, when an exception is thrown, it cannot be ignored--there must be some kind of notification or termination of the program. If no user-provided exception handler is present, the compiler provides a default mechanism to terminate the program.

Exception handling is expensive compared to ordinary program flow controls, such as loops or if-statements. It is therefore better not to use the exception mechanism to deal with ordinary situations, but to reserve it for situations that are truly unusual.

Exceptions are particularly helpful in dealing with situations that cannot be handled locally. Instead of propagating error status throughout the program, you can transfer control directly to the point where the error can be handled.

For example, a function might have the job of opening a file and initializing some associated data. If the file cannot be opened or is corrupted, the function cannot do its job. However, that function might not have enough information to handle the problem. The function can throw an exception object that describes the problem, transferring control to an earlier point in the program. The exception handler might automatically try a backup file, query the user for another file to try, or shut down the program gracefully. Without exception handlers, status and data would have to be passed down and up the function call hierarchy, with status checks after every function call. With exception handlers, the flow of control is not obscured by error checking. If a function returns, the caller can be certain that it succeeded.

Exception handlers have disadvantages. If a function does not return because it, or some other function it called, threw an exception, data might be left in an inconsistent state. You need to know when an exception might be thrown, and whether the exception might have a bad effect on the program state.

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.

Listing 1: Code inside the try block will be monitored

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.

Listing 2: Else statement code

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.

Listing 3: Illustrates catch statement

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

Exception 003

The above examples are designed to show how try, throw, and catch work. But, they are not always useful in a real world C++ program. However, the example below will show how exception handling can be more realistically written 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.

Listing 4: Advanced Exception Handling

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.

Listing 5: Using variables str_error and why1

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 asks 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 caught 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.

Conclusion

This brings us to an end of this article where we learnt on the exception handling techniques to be followed in C++.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login