C++ try and catch statements code on computer screen

Blog Tech C++ Try and Catch Statements Explained

C++ Try and Catch Statements Explained

Every useful program eventually runs into states the developer didn’t expect. Users can introduce errors by inputting values that don’t make sense. Sometimes, the developer of the program didn’t think through all the possibilities or wasn’t aware of future changes in the environment or libraries.

C++ has a try-catch construct specifically to deal with unexpected errors like this, regardless of the cause of each error. To understand how try-catch works in C++, let’s first take a look at exceptions.

What Are Exceptions in C++?

Errors can appear in code either during the compilation stage or while the program is running. Logical and syntax errors appearing in code during compilation will need to be resolved by the C++ developer in charge. There’s no hope of using your code until these issues have been resolved.

Should your code pass all the compiler’s checks, it will be ready to enter a runtime state. Exceptions occur in C++ when errors or abnormal conditions take place while code is running.

An example of an exception “being raised” is  where the program tries to divide by a variable which happens to have the value zero:

#include <iostream>

using namespace std;

int divide(int num, int den) {
    return (num / den);
}

int main()
{
    int top, bottom; // Declare variables
    cout << "Enter the numerator: "; // Input numerator
    cin  >> top;
    cout << "Enter the denominator: "; // Input denominator
    cin  >> bottom;
    int answer = divide(top,bottom); // Perform calculation
    cout << answer; // Output answer

    return 0;
}

This code works for any integer values unless you input a 0 for bottom. Doing so results in an exception:

Enter the numerator: 4Enter the denominator: 0[1]    34636 floating point exception

The program compiled just fine but took issue with the user-inputted denominator.

In the case of our example, a programmer should assume that someone will eventually put a zero in for the denominator, intentionally or otherwise. Instead of having the operating system forcingly shut down our program every time something unexpected happens, C++ provides exception handling functions to capture and take care of those exceptions.

Note: In addition to exceptions, programs written in C++ or any other language can receive signals from the operating system. Signals are messages that the operating system uses to notify the program when, for example, there is new data available on the program’s network connection or there has been input from the keyboard. Signals aren’t treated as exceptions in C++ and are not covered in this article. 

What Is Exception Handling?

In C++, exception handling is a means for code to identify and deal with runtime errors. A C++ program is able to use a unique set of functions called handlers to keep a watchful eye on a particular section of the program’s code. These handlers will catch any exceptions in that section of code as they appear during runtime, reacting accordingly.

Adding exception handlers to your program causes no penalty in speed; if there are no exceptions raised the handlers will simply never be used. Not adding exception handlers to your code results in fragile code.

Although the C and the C++ programming languages have many similarities, exception handling is one significant difference. Handlers and their ability to react to exceptions do not exist in C, and programmers are forced to plan exceptions out of their code instead of being able to react to them if and when they happen.

Advantages of Exception Handling

While the approach mentioned above is also possible in C++, there are notable reasons why exception handling exists and is the recommended course of action.

Separation of normal work flow from error handling code

Using if/else statements in C++ can work around exceptions in code, but these quickly become lost among other if/else statements in your program. Managing exceptions with if/else with the normal flow of your code can lead to readability issues and confusion, especially since exception handling code will not always be run. Adding if/else statements to your code can result in duplicate code, something that well-designed exception handlers mitigate.

Using exception handler functions specifically identifies that a block of code is reserved for dealing with errors as these appear in runtime. This makes it easy to locate and maintain exception handling code and gives your overall program a cleaner look.

Grouping of types

Both objects and data types can be used for identifying exceptions in code. This makes it possible to group exceptions according to data type or create a hierarchy of objects. For example, you can create your own type of exception and use it where appropriate instead of C++’s built-in exception types.

Control over exceptions

As a C++ programmer, you’re able to address whichever exceptions you want, even if a function has many. It then falls upon the caller of your function to handle any uncaught exceptions, or, if there are no caller functions, the error handling ultimately falls upon the operating system.

Try, Catch and Throw Exception Handling Functions

Let’s take a look at the three concepts that C++ uses to tackle exception handling in code.

The try block

Try blocks are used to enclose statements that may return an exception. These blocks need to be followed up by one or more catch blocks.

The throw expression

When an exception occurs in a try block, the conveniently named throw expression takes the exception and throws it to be caught by the catch clause. The operand listed in the throw function determines the exception’s type.

The catch clause

To make use of a try block, you must also add a catch clause to your program. A catch block specifies the type of exception it can handle and allows you to define the code executed when the error occurs.

How To Implement Exception Handling in Code

The code below shows how a try-block deals with an exception:

try {  // This is the block of code that contains potential exceptions  throw exception; // Throws an exception and identifies the data type}catch () {  // This block explains what to do when an exception happens}

Let’s revisit our earlier example and use try-catch in C++ to output an error message if someone tries to put in a zero for the denominator value.

#include <iostream>

using namespace std;

int divide(int num, int den) {
    if (den == 0) {
        // Throw an exception with this text if the denominator
        // is zero
        throw "You can't divide by zero!";
    }
    return (num / den);
}

int main()
{
    int top, bottom; // Declare variables
    cout << "Enter the numerator: "; // Input numerator
    cin  >> top;
    cout << "Enter the denominator: "; // Input denominator
    cin  >> bottom;
    try {   // Add in the try block where the exception could take place
        int answer = divide(top,bottom); // Perform calculation
          cout << answer; // Output answer
    }
    // The catch block activates when the try block produces an exception
    catch (const char* message) { // Catches a throw with same data type
        cout << message << endl; // Outputs information about exception
    }
 
    return 0;
}

We kept most of the code in both divide and main. However, the calculation that can result in an exception is now placed inside the try block, enabling the program to keep an eye out for errors.

This is followed up by the catch statement that will output the error message if and only if an exception occurs. When the try block returns an exception, the catch function begins searching for a const char data type that’s been thrown. If there’s no exception, the program will skip this code and simply return the answer to the division operation.

When the denominator is zero, the program will throw the const char "You can't divide by zero!". This gets caught by the catch block so the program can let the user know they’ve used a value that does not work.

Besides the method we describe above, you can modify the catch statement to be more specific, for example, only handle a runtime error rather than any type of exception. One more option is to create our own exception class, say, TriedToDivideByZeroException, as a sub-class of runtime_error and use our class in the throw and catch statements.

Learn C++ Online With Udacity

If you’re a C++ novice, you may find it tricky to use try-catch when coding. But as we’ve seen above, try-catch is a very useful tool for addressing exceptions and streamlining your code.

Ready to take the next step? 

At Udacity, we offer a specialized C++ Nanodegree that’s focused on real-world problems that C++ developers face on a daily basis.

Enroll in our C++ Nanodegree program today!

Stay updated on the latest in technology

"*" indicates required fields

Stay updated on the Latest in Tech

Be first to hear about special offers, news, and resources from Udacity

"*" indicates required fields