C++ Tutorial #21 – Exception Handling

Facebooktwittergoogle_plusredditpinterestlinkedinmail

In C++, we use exception handling (also called try/catch statements) to allow our program to react to conditions such as runtime errors. This is done by transferring control of the program to special functions called handlers.

 

To write an exception, you create a try & catch block. Inside of the try block, the exception is thrown by using the keyword throw. The handlers are declared using the catch block, which is placed after the try block.

 

Here’s an example:

 

try
{
throw 25;
}
catch (int exNum)
{
cout << “An exception occurred: Exception #” << exNum << ‘\n’;
}

 

In this example, in the try block, the exception throws a 25. In the catch block, the exception takes the number that was thrown and prints it out.

 



 

Let’s get started on writing a program on our own using exceptions:

 

 




 

If done correctly, your program should look something like this:

 

what month were you born? (Enter in numbers): 1

day? 1

year? 2000

Your birth date is: 1/1/2000.

 

The example above is how the program should look if the user enters in all valid numbers. If the user placed a number greater than 12 (for example; 14), the program with throw out a 10. Look at the other examples below to see what I mean:

 

what month were you born? (Enter in numbers): 14

day? 24

year? 1990

An exception occurred. Exception #10
Your birth date is: 14/24/1990.

 

what month were you born? (Enter in numbers): 7

day? 50

year? 1983

An exception occurred. Exception #20
Your birth date is: 7/50/1983.

 

what month were you born? (Enter in numbers): 4

day? 20

year? 3047

An exception occurred. Exception #30
Your birth date is: 4/20/3047.

 

As you can see, the program still continues after the exception number is thrown, but it lets the user know where the error is located in the program.

 

I’ll end the tutorial here today, I won’t break down the program and explain each part today because a lot of what we used in today’s lesson was basic stuff. This lesson was quick and easy, just a break to get you prepared for the harder lessons we will do soon. Right now, there really isn’t much use for exception handling, in fact, they’re totally optional, but it’s good practice to learn every part there is in C++ programming. Don’t forget to like, share, & subscribe. Thank you for reading!

 

Facebooktwittergoogle_plusredditpinterestlinkedinmail

About Justin

Computer programmer and owner of kauergames.com.
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *