← C++ from Scratch Lesson 49 of 62 · 10 XP

Exceptions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An exception is a way to report an error that can't be handled on the spot:

#include <stdexcept>

double safeDiv(double a, double b)
{
    if (b == 0)
        throw std::invalid_argument("division by zero");   // throw
    return a / b;
}

try {
    std::cout << safeDiv(1, 0);
} catch (const std::invalid_argument &e) {               // catch by type
    std::cout << "Error: " << e.what() << '\n';
} catch (const std::exception &e) {                     // the base class of all standard exceptions
    std::cout << "Something went wrong: " << e.what() << '\n';
}

A thrown exception unwinds the stack: it leaves functions one after another, calling destructors (that's why RAII objects free resources correctly), until a matching catch is found. noexcept on a function promises that there will be no exceptions.

Important about this site. The C++ compiler in the browser is built without exception support (-fno-exceptions): try and throw won't compile here. On your own computer (g++, clang++, MSVC) they work. So the practice here is the second way, without exceptions, which is popular in games and systems code: returning "a result or nothing" — std::optional from <optional>:

std::optional<int> parseAge(const std::string &s)
{
    if (s.empty()) return std::nullopt;     // "nothing"
    …
    return age;
}
if (auto a = parseAge(text)) std::cout << *a;   // *a is the value
else std::cout << "invalid";

Task. Write std::optional<int> safeDiv(int a, int b) (when b == 0 — std::nullopt) and std::optional<int> parseInt(const std::string&) (only digits with an optional minus, otherwise nullopt). Read n lines of the form A B; for each, print the quotient, bad number or division by zero.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.