Codiqo

Learn C++ · lesson 44 of 61 · about 9 minutes

Exceptions

Sell loot to the merchant: signal problems with throw, handle them with try and catch, and use the standard exception types.

What you'll learn

  • Throw a standard exception
  • Catch by const reference
  • Read the message with what()

The merchant

A merchant at the foot of the stairs buys loot: 15 gold for a gem, 20 for a ring, 50 for a crown. merchantPrice(item) returns the price, and for anything else it can't return a sensible number, so it throws std::invalid_argument("The merchant won't buy the " + item). The selling loop calls it inside try, adds the gold when it works, and in catch (const std::invalid_argument& e) prints e.what(), then goes on to the next item.

When something can't be done

throw std::invalid_argument("..."); stops the function and jumps to the nearest matching catch. Standard exceptions live in <stdexcept>:

| Type | Use for |
|---|---|
| std::invalid_argument | a bad value was passed in |
| std::out_of_range | an index or key doesn't exist |
| std::runtime_error | something failed while running |

Catch by const reference: catch (const std::exception& e), and read the message with e.what().

Throwing and catching

#include <iostream>
#include <stdexcept>
#include <vector>

int withdraw(int balance, int amount) {
    if (amount <= 0) throw std::invalid_argument("amount must be positive");
    if (amount > balance) throw std::runtime_error("insufficient funds");
    return balance - amount;
}

int main() {
    try {
        std::cout << withdraw(50, 20) << "\n";
        std::cout << withdraw(50, 80) << "\n";
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << "\n";
    }

    std::vector<int> v = {1, 2};
    try {
        std::cout << v.at(5) << "\n";
    } catch (const std::out_of_range&) {
        std::cout << "No item 5\n";
    }
}

Output

30
Error: insufficient funds
No item 5

Tip

Catch the most specific types first. catch (const std::exception&) catches every standard exception, so put it last.

One try for each item

Put the try inside the loop, around the one call that might throw, and a refused item is reported while the loop carries on with the next. An exception that nothing catches ends the whole program, with a message like terminate called after throwing an instance of 'std::invalid_argument'.

A message built from the input

#include <iostream>
#include <stdexcept>
#include <string>

int priceOf(const std::string& item) {
    if (item == "gem") return 15;
    throw std::invalid_argument("no price for " + item);
}

int main() {
    for (std::string item : {"gem", "boot", "gem"}) {
        try {
            std::cout << priceOf(item) << "\n";
        } catch (const std::invalid_argument& e) {
            std::cout << e.what() << "\n";
        }
    }
}

Output

15
no price for boot
15

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.