Throwing Exceptions in C++

Lesson Introduction

Hello! Today, we will learn about throwing exceptions in C++, which is vital for writing robust programs. Think of exceptions like traffic signals. When driving, if you see a red light, you stop to avoid collisions—a clear sign something needs attention. Similarly, exceptions signal problems in our code, allowing us to handle errors smoothly. By the end, you'll know how to throw and catch exceptions, making your programs more resilient.

Throwing Exceptions

To "throw" an exception means to signal that something unusual has occurred. In C++, we use the throw keyword to do this. It’s like raising your hand to say, "Wait, there's a problem!"

Here’s a simple example. Imagine you ask a vending machine for a snack that's out of stock. The machine needs to inform you that it can't complete your request:

#include <iostream>
#include <stdexcept> // For std::runtime_error


int main() {
    int stock = 0;
    if (stock == 0) {
        throw std::runtime_error("Out of stock!");
    }
    return 0;
}

Output:

terminate called after throwing an instance of 'std::runtime_error'
  what():  Out of stock!

Catching Exceptions: Part 1

Imagine we have a function that can throw an error:

#include <iostream>
#include <stdexcept>

void give_order(int order, int stock) {
    if (order <= stock) {
        std::cout << "Here is your order!" << std::endl;
    } else {
        throw std::runtime_error("Out of stock!");
    }
}

int main() {
    give_order(1, 10);  // Here is your order!
}

In this case, everything is fine, and the function is successfully executed. But if we call it like this, it will throw an error:

int main() {
    give_order(5, 0); 
    // terminate called after throwing an instance of 'std::runtime_error'
    // what():  Out of stock!
}

This way, our function is designed to warn the program with an error that something went wrong. However, we don't want the program to terminate every time this error appears. Let's learn how to handle it.

Catching Exceptions: Part 2

In C++, we can handle exceptions with a special try-catch block. The program tries to execute the code inside the try, and in case it fails with an exception, executes the code inside the catch.

Let’s modify our example:

int main() {
    int order = 5;
    int stock = 3;

    try {
        give_order(order, stock);
    } catch (const std::runtime_error& e) {
        std::cout << "Error: " << e.what() << std::endl;
    }

    return 0;
}

When the give_order function is called with order = 5 and stock = 3, it will throw a std::runtime_error because the order exceeds the stock.

The catch block catches exceptions of type std::runtime_error. If the exception is caught, it prints the error message using e.what() where e is the exception object caught. This prevents the program from crashing and allows you to handle the error however you want.

This way, your program continues to run and provides a meaningful handling of an error.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal