Skip to main content

Exceptions: throw, try, catch

intermediate25 min readLesson 117 of 204

The standard exception family, catch-by-const-ref, handler ordering, and when exceptions beat return codes.

C++ error handling has two channels: return values for expected outcomes, and exceptions for conditions the caller cannot quietly ignore.

#include <stdexcept>

int parse_port(const std::string& s) {
    int value = std::stoi(s);          // throws std::invalid_argument
    if (value < 0 || value > 65535)
        throw std::out_of_range("port out of range: " + s);
    return value;
}

The throwing family you will actually use, all in <stdexcept>:

  • std::invalid_argument โ€” the input is not parseable
  • std::out_of_range โ€” parseable but outside the legal domain
  • std::runtime_error โ€” failures only visible at runtime (I/O, network)
  • std::logic_error โ€” the program broke its own contract

Throw by value, catch by const&:

try {
    int port = parse_port(user_input);
    use(port);
} catch (const std::out_of_range& e) {
    std::cerr << "bad port: " << e.what() << "\n";
} catch (const std::exception& e) {
    std::cerr << "error: " << e.what() << "\n";   // base-class fallback
}

Catch order matters: handlers are tried top-down, so put derived types before bases. A bare catch (...) swallows everything โ€” reserve it for thread boundaries and last-resort barriers.

Now practice

Exception practiceType-precise validation and unguarded-stoi recovery.1 challenge ยท ยท ~30 min