Lesson 20 — Robustness

Exception Handling

Exceptions let a program signal that something has gone wrong and hand control to code specifically written to deal with that failure, rather than crashing or silently producing wrong results.

try, catch, and throw

Code that might fail is placed inside a try block. If something goes wrong, throw raises an exception, which is caught by a matching catch block that handles the problem without terminating the whole program.

C++ — Basic exception handling
double divide(double a, double b) {
    if (b == 0) {
        throw std::runtime_error("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        std::cout << divide(10, 0) << std::endl;
    } catch (const std::runtime_error &e) {
        std::cout << "Error: " << e.what() << std::endl;
    }
    std::cout << "Program continues normally." << std::endl;
    return 0;
}

Standard Exception Types

The <stdexcept> header provides several ready-made exception classes you can throw and catch instead of inventing your own for common situations.

  • std::runtime_error — for errors detectable only at runtime.
  • std::invalid_argument — for a function receiving an unacceptable argument.
  • std::out_of_range — for accessing an invalid index, such as with .at() on a vector.
  • std::logic_error — for errors that stem from a violated precondition in the program's logic.

Common Mistakes

  • Catching exceptions by value instead of by const reference, which causes unnecessary copying and can slice derived exception types.
  • Using exceptions for normal, expected control flow rather than genuinely exceptional situations — this hurts both performance and readability.
  • Forgetting that an uncaught exception terminates the entire program.
  • Writing an overly broad catch (...) that hides the real cause of a failure instead of catching specific, informative exception types.

Professional Tip

Order your catch blocks from most specific exception type to least specific. If a general catch (const std::exception&) comes first, it will intercept every exception before more specific handlers ever get a chance to run.

Your Turn

Write a function that takes an array index and an array size, and throws std::out_of_range if the index is invalid. Call it inside a try/catch and print a friendly error message when caught.

Mini Quiz

What keyword is used to raise (signal) an exception in C++?