`throw` — C++ Keyword

`throw` — C++ Keyword

The throw keyword in C++: raises an exception or re-throws the current one.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

throw

Raises an exception, transferring control to the nearest matching catch clause. Used without an operand inside a catch, it re-throws the current exception.

Syntax

throw expression;   // throw a new exception
throw;              // re-throw the current exception (inside catch only)

Example

#include <print>
#include <stdexcept>

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

void log_and_rethrow() {
    try {
        divide(1.0, 0.0);
    } catch (...) {
        std::println("Logging error before re-throw...");
        throw;   // re-throws the std::invalid_argument
    }
}

int main() {
    try {
        log_and_rethrow();
    } catch (const std::invalid_argument& e) {
        std::println("Caught: {}", e.what());
    }
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}