2.5.2 Validating a Number

The basic error handling process in C++ uses what is called a try/catch block. This concept is similar in Java and basically is like an if/else block. If the code runs without error, use the try block, otherwise use the catch block.

Try/Catch Setup

As mentioned above, the try/catch block is like a conditional statement block. You put your code that may cause an error into the try portion of the block. When C++ executes the try block, if a valid exception occurs, it will move to the catch block of code and execute that code.

Here is the basic syntax for a try/catch in C++:

try {
    // Block of code to execute that may
    // cause an error
}
catch (error type) {
    // Block of code to execute if the error type
    // is generated
}

The term catch comes from the idea that your program will throw an error if a problem occurs. If you notice in the example above, the type of error code that you are catching needs to be specified. This allows you to handle different error types based on what error the program throws. It is possible to generically catch all errors in one block, but allowing you to specify provides more control for the developer.

Example

Over the course of this lesson, you will see several different examples of error handling and throwing/catching errors. This example demonstrates basic functionality of ensuring that a user enters a number when prompted. If the user were to enter a letter, C++ would not crash, but it would not process the value correctly.

To get around this, you can write a program that will read in a value as a string. Once you have the string, you are going to attempt to convert it to an integer. If the conversion works, you know that the number is valid and can move on.

If the user enters something other than a number, the stoi command will throw an invalid argument error that you can catch and deal with.

Last updated